##// END OF EJS Templates
A new SendToServer Unit has been created to upload files to a remote server....
Miguel Valdez -
r573:e93e8802031b
parent child
Show More
@@ -0,0 +1,27
1 '''
2 @author: roj-idl71
3 '''
4 #USED IN jroplot_spectra.py
5 RTI_CODE = 0 #Range time intensity (RTI).
6 SPEC_CODE = 1 #Spectra (and Cross-spectra) information.
7 CROSS_CODE = 2 #Cross-Correlation information.
8 COH_CODE = 3 #Coherence map.
9 BASE_CODE = 4 #Base lines graphic.
10 ROW_CODE = 5 #Row Spectra.
11 TOTAL_CODE = 6 #Total Power.
12 DRIFT_CODE = 7 #Drifts graphics.
13 HEIGHT_CODE = 8 #Height profile.
14 PHASE_CODE = 9 #Signal Phase.
15
16 POWER_CODE = 16
17 NOISE_CODE = 17
18 BEACON_CODE = 18
19
20 #USED IN jroplot_parameters.py
21
22 MOMENTS_CODE = 20
23 SKYMAP_CODE = 21
24 WIND_CODE = 22
25 PARMS_CODE = 23
26 SPECFIT_CODE = 24
27 EWDRIFT_CODE = 25
@@ -0,0 +1,464
1 # scp.py
2 # Copyright (C) 2008 James Bardin <j.bardin@gmail.com>
3
4 """
5 Utilities for sending files over ssh using the scp1 protocol.
6 """
7
8 __version__ = '0.10.0'
9
10 import locale
11 import os
12 import re
13 from socket import timeout as SocketTimeout
14
15
16 # this is quote from the shlex module, added in py3.3
17 _find_unsafe = re.compile(br'[^\w@%+=:,./~-]').search
18
19
20 def _sh_quote(s):
21 """Return a shell-escaped version of the string `s`."""
22 if not s:
23 return b""
24 if _find_unsafe(s) is None:
25 return s
26
27 # use single quotes, and put single quotes into double quotes
28 # the string $'b is then quoted as '$'"'"'b'
29 return b"'" + s.replace(b"'", b"'\"'\"'") + b"'"
30
31
32 # Unicode conversion functions; assume UTF-8
33
34 def asbytes(s):
35 """Turns unicode into bytes, if needed.
36 Assumes UTF-8.
37 """
38 if isinstance(s, bytes):
39 return s
40 else:
41 return s.encode('utf-8')
42
43
44 def asunicode(s):
45 """Turns bytes into unicode, if needed.
46 Uses UTF-8.
47 """
48 if isinstance(s, bytes):
49 return s.decode('utf-8', 'replace')
50 else:
51 return s
52
53
54 # os.path.sep is unicode on Python 3, no matter the platform
55 bytes_sep = asbytes(os.path.sep)
56
57
58 # Unicode conversion function for Windows
59 # Used to convert local paths if the local machine is Windows
60
61 def asunicode_win(s):
62 """Turns bytes into unicode, if needed.
63 """
64 if isinstance(s, bytes):
65 return s.decode(locale.getpreferredencoding())
66 else:
67 return s
68
69
70 class SCPClient(object):
71 """
72 An scp1 implementation, compatible with openssh scp.
73 Raises SCPException for all transport related errors. Local filesystem
74 and OS errors pass through.
75 Main public methods are .put and .get
76 The get method is controlled by the remote scp instance, and behaves
77 accordingly. This means that symlinks are resolved, and the transfer is
78 halted after too many levels of symlinks are detected.
79 The put method uses os.walk for recursion, and sends files accordingly.
80 Since scp doesn't support symlinks, we send file symlinks as the file
81 (matching scp behaviour), but we make no attempt at symlinked directories.
82 """
83 def __init__(self, transport, buff_size=16384, socket_timeout=5.0,
84 progress=None, sanitize=_sh_quote):
85 """
86 Create an scp1 client.
87 @param transport: an existing paramiko L{Transport}
88 @type transport: L{Transport}
89 @param buff_size: size of the scp send buffer.
90 @type buff_size: int
91 @param socket_timeout: channel socket timeout in seconds
92 @type socket_timeout: float
93 @param progress: callback - called with (filename, size, sent) during
94 transfers
95 @param sanitize: function - called with filename, should return
96 safe or escaped string. Uses _sh_quote by default.
97 @type progress: function(string, int, int)
98 """
99 self.transport = transport
100 self.buff_size = buff_size
101 self.socket_timeout = socket_timeout
102 self.channel = None
103 self.preserve_times = False
104 self._progress = progress
105 self._recv_dir = b''
106 self._rename = False
107 self._utime = None
108 self.sanitize = sanitize
109 self._dirtimes = {}
110
111 def __enter__(self):
112 self.channel = self._open()
113 return self
114
115 def __exit__(self, type, value, traceback):
116 self.close()
117
118 def put(self, files, remote_path=b'.',
119 recursive=False, preserve_times=False):
120 """
121 Transfer files to remote host.
122 @param files: A single path, or a list of paths to be transfered.
123 recursive must be True to transfer directories.
124 @type files: string OR list of strings
125 @param remote_path: path in which to receive the files on the remote
126 host. defaults to '.'
127 @type remote_path: str
128 @param recursive: transfer files and directories recursively
129 @type recursive: bool
130 @param preserve_times: preserve mtime and atime of transfered files
131 and directories.
132 @type preserve_times: bool
133 """
134 self.preserve_times = preserve_times
135 self.channel = self._open()
136 self._pushed = 0
137 self.channel.settimeout(self.socket_timeout)
138 scp_command = (b'scp -t ', b'scp -r -t ')[recursive]
139 self.channel.exec_command(scp_command +
140 self.sanitize(asbytes(remote_path)))
141 self._recv_confirm()
142
143 if not isinstance(files, (list, tuple)):
144 files = [files]
145
146 if recursive:
147 self._send_recursive(files)
148 else:
149 self._send_files(files)
150
151 self.close()
152
153 def get(self, remote_path, local_path='',
154 recursive=False, preserve_times=False):
155 """
156 Transfer files from remote host to localhost
157 @param remote_path: path to retreive from remote host. since this is
158 evaluated by scp on the remote host, shell wildcards and
159 environment variables may be used.
160 @type remote_path: str
161 @param local_path: path in which to receive files locally
162 @type local_path: str
163 @param recursive: transfer files and directories recursively
164 @type recursive: bool
165 @param preserve_times: preserve mtime and atime of transfered files
166 and directories.
167 @type preserve_times: bool
168 """
169 if not isinstance(remote_path, (list, tuple)):
170 remote_path = [remote_path]
171 remote_path = [self.sanitize(asbytes(r)) for r in remote_path]
172 self._recv_dir = local_path or os.getcwd()
173 self._rename = (len(remote_path) == 1 and
174 not os.path.isdir(os.path.abspath(local_path)))
175 if len(remote_path) > 1:
176 if not os.path.exists(self._recv_dir):
177 raise SCPException("Local path '%s' does not exist" %
178 asunicode(self._recv_dir))
179 elif not os.path.isdir(self._recv_dir):
180 raise SCPException("Local path '%s' is not a directory" %
181 asunicode(self._recv_dir))
182 rcsv = (b'', b' -r')[recursive]
183 prsv = (b'', b' -p')[preserve_times]
184 self.channel = self._open()
185 self._pushed = 0
186 self.channel.settimeout(self.socket_timeout)
187 self.channel.exec_command(b"scp" +
188 rcsv +
189 prsv +
190 b" -f " +
191 b' '.join(remote_path))
192 self._recv_all()
193 self.close()
194
195 def _open(self):
196 """open a scp channel"""
197 if self.channel is None:
198 self.channel = self.transport.open_session()
199
200 return self.channel
201
202 def close(self):
203 """close scp channel"""
204 if self.channel is not None:
205 self.channel.close()
206 self.channel = None
207
208 def _read_stats(self, name):
209 """return just the file stats needed for scp"""
210 if os.name == 'nt':
211 name = asunicode(name)
212 stats = os.stat(name)
213 mode = oct(stats.st_mode)[-4:]
214 size = stats.st_size
215 atime = int(stats.st_atime)
216 mtime = int(stats.st_mtime)
217 return (mode, size, mtime, atime)
218
219 def _send_files(self, files):
220 for name in files:
221 basename = asbytes(os.path.basename(name))
222 (mode, size, mtime, atime) = self._read_stats(name)
223 if self.preserve_times:
224 self._send_time(mtime, atime)
225 file_hdl = open(name, 'rb')
226
227 # The protocol can't handle \n in the filename.
228 # Quote them as the control sequence \^J for now,
229 # which is how openssh handles it.
230 self.channel.sendall(("C%s %d " % (mode, size)).encode('ascii') +
231 basename.replace(b'\n', b'\\^J') + b"\n")
232 self._recv_confirm()
233 file_pos = 0
234 if self._progress:
235 if size == 0:
236 # avoid divide-by-zero
237 self._progress(basename, 1, 1)
238 else:
239 self._progress(basename, size, 0)
240 buff_size = self.buff_size
241 chan = self.channel
242 while file_pos < size:
243 chan.sendall(file_hdl.read(buff_size))
244 file_pos = file_hdl.tell()
245 if self._progress:
246 self._progress(basename, size, file_pos)
247 chan.sendall('\x00')
248 file_hdl.close()
249 self._recv_confirm()
250
251 def _chdir(self, from_dir, to_dir):
252 # Pop until we're one level up from our next push.
253 # Push *once* into to_dir.
254 # This is dependent on the depth-first traversal from os.walk
255
256 # add path.sep to each when checking the prefix, so we can use
257 # path.dirname after
258 common = os.path.commonprefix([from_dir + bytes_sep,
259 to_dir + bytes_sep])
260 # now take the dirname, since commonprefix is character based,
261 # and we either have a seperator, or a partial name
262 common = os.path.dirname(common)
263 cur_dir = from_dir.rstrip(bytes_sep)
264 while cur_dir != common:
265 cur_dir = os.path.split(cur_dir)[0]
266 self._send_popd()
267 # now we're in our common base directory, so on
268 self._send_pushd(to_dir)
269
270 def _send_recursive(self, files):
271 for base in files:
272 if not os.path.isdir(base):
273 # filename mixed into the bunch
274 self._send_files([base])
275 continue
276 last_dir = asbytes(base)
277 for root, dirs, fls in os.walk(base):
278 self._chdir(last_dir, asbytes(root))
279 self._send_files([os.path.join(root, f) for f in fls])
280 last_dir = asbytes(root)
281 # back out of the directory
282 while self._pushed > 0:
283 self._send_popd()
284
285 def _send_pushd(self, directory):
286 (mode, size, mtime, atime) = self._read_stats(directory)
287 basename = asbytes(os.path.basename(directory))
288 if self.preserve_times:
289 self._send_time(mtime, atime)
290 self.channel.sendall(('D%s 0 ' % mode).encode('ascii') +
291 basename.replace(b'\n', b'\\^J') + b'\n')
292 self._recv_confirm()
293 self._pushed += 1
294
295 def _send_popd(self):
296 self.channel.sendall('E\n')
297 self._recv_confirm()
298 self._pushed -= 1
299
300 def _send_time(self, mtime, atime):
301 self.channel.sendall(('T%d 0 %d 0\n' % (mtime, atime)).encode('ascii'))
302 self._recv_confirm()
303
304 def _recv_confirm(self):
305 # read scp response
306 msg = b''
307 try:
308 msg = self.channel.recv(512)
309 except SocketTimeout:
310 raise SCPException('Timout waiting for scp response')
311 # slice off the first byte, so this compare will work in py2 and py3
312 if msg and msg[0:1] == b'\x00':
313 return
314 elif msg and msg[0:1] == b'\x01':
315 raise SCPException(asunicode(msg[1:]))
316 elif self.channel.recv_stderr_ready():
317 msg = self.channel.recv_stderr(512)
318 raise SCPException(asunicode(msg))
319 elif not msg:
320 raise SCPException('No response from server')
321 else:
322 raise SCPException('Invalid response from server', msg)
323
324 def _recv_all(self):
325 # loop over scp commands, and receive as necessary
326 command = {b'C': self._recv_file,
327 b'T': self._set_time,
328 b'D': self._recv_pushd,
329 b'E': self._recv_popd}
330 while not self.channel.closed:
331 # wait for command as long as we're open
332 self.channel.sendall('\x00')
333 msg = self.channel.recv(1024)
334 if not msg: # chan closed while recving
335 break
336 assert msg[-1:] == b'\n'
337 msg = msg[:-1]
338 code = msg[0:1]
339 try:
340 command[code](msg[1:])
341 except KeyError:
342 raise SCPException(asunicode(msg[1:]))
343 # directory times can't be set until we're done writing files
344 self._set_dirtimes()
345
346 def _set_time(self, cmd):
347 try:
348 times = cmd.split(b' ')
349 mtime = int(times[0])
350 atime = int(times[2]) or mtime
351 except:
352 self.channel.send(b'\x01')
353 raise SCPException('Bad time format')
354 # save for later
355 self._utime = (atime, mtime)
356
357 def _recv_file(self, cmd):
358 chan = self.channel
359 parts = cmd.strip().split(b' ', 2)
360
361 try:
362 mode = int(parts[0], 8)
363 size = int(parts[1])
364 if self._rename:
365 path = self._recv_dir
366 self._rename = False
367 elif os.name == 'nt':
368 path = os.path.join(asunicode_win(self._recv_dir),
369 parts[2].decode('utf-8'))
370 else:
371 path = os.path.join(asbytes(self._recv_dir),
372 parts[2])
373 except:
374 chan.send('\x01')
375 chan.close()
376 raise SCPException('Bad file format')
377
378 try:
379 file_hdl = open(path, 'wb')
380 except IOError as e:
381 chan.send(b'\x01' + str(e).encode('utf-8'))
382 chan.close()
383 raise
384
385 if self._progress:
386 if size == 0:
387 # avoid divide-by-zero
388 self._progress(path, 1, 1)
389 else:
390 self._progress(path, size, 0)
391 buff_size = self.buff_size
392 pos = 0
393 chan.send(b'\x00')
394 try:
395 while pos < size:
396 # we have to make sure we don't read the final byte
397 if size - pos <= buff_size:
398 buff_size = size - pos
399 file_hdl.write(chan.recv(buff_size))
400 pos = file_hdl.tell()
401 if self._progress:
402 self._progress(path, size, pos)
403
404 msg = chan.recv(512)
405 if msg and msg[0:1] != b'\x00':
406 raise SCPException(asunicode(msg[1:]))
407 except SocketTimeout:
408 chan.close()
409 raise SCPException('Error receiving, socket.timeout')
410
411 file_hdl.truncate()
412 try:
413 os.utime(path, self._utime)
414 self._utime = None
415 os.chmod(path, mode)
416 # should we notify the other end?
417 finally:
418 file_hdl.close()
419 # '\x00' confirmation sent in _recv_all
420
421 def _recv_pushd(self, cmd):
422 parts = cmd.split(b' ', 2)
423 try:
424 mode = int(parts[0], 8)
425 if self._rename:
426 path = self._recv_dir
427 self._rename = False
428 elif os.name == 'nt':
429 path = os.path.join(asunicode_win(self._recv_dir),
430 parts[2].decode('utf-8'))
431 else:
432 path = os.path.join(asbytes(self._recv_dir),
433 parts[2])
434 except:
435 self.channel.send(b'\x01')
436 raise SCPException('Bad directory format')
437 try:
438 if not os.path.exists(path):
439 os.mkdir(path, mode)
440 elif os.path.isdir(path):
441 os.chmod(path, mode)
442 else:
443 raise SCPException('%s: Not a directory' % path)
444 self._dirtimes[path] = (self._utime)
445 self._utime = None
446 self._recv_dir = path
447 except (OSError, SCPException) as e:
448 self.channel.send(b'\x01' + asbytes(str(e)))
449 raise
450
451 def _recv_popd(self, *cmd):
452 self._recv_dir = os.path.split(self._recv_dir)[0]
453
454 def _set_dirtimes(self):
455 try:
456 for d in self._dirtimes:
457 os.utime(d, self._dirtimes[d])
458 finally:
459 self._dirtimes = {}
460
461
462 class SCPException(Exception):
463 """SCP exception class"""
464 pass No newline at end of file
@@ -1,844 +1,855
1 '''
1 '''
2 Created on September , 2012
2 Created on September , 2012
3 @author:
3 @author:
4 '''
4 '''
5 from xml.etree.ElementTree import Element, SubElement
5 from xml.etree.ElementTree import Element, SubElement
6 from xml.etree import ElementTree as ET
6 from xml.etree import ElementTree as ET
7 from xml.dom import minidom
7 from xml.dom import minidom
8
8
9 #import datetime
9 #import datetime
10 from model import *
10 from model import *
11
11
12 import ast
12 import ast
13
13
14 def prettify(elem):
14 def prettify(elem):
15 """Return a pretty-printed XML string for the Element.
15 """Return a pretty-printed XML string for the Element.
16 """
16 """
17 rough_string = ET.tostring(elem, 'utf-8')
17 rough_string = ET.tostring(elem, 'utf-8')
18 reparsed = minidom.parseString(rough_string)
18 reparsed = minidom.parseString(rough_string)
19 return reparsed.toprettyxml(indent=" ")
19 return reparsed.toprettyxml(indent=" ")
20
20
21 class ParameterConf():
21 class ParameterConf():
22
22
23 id = None
23 id = None
24 name = None
24 name = None
25 value = None
25 value = None
26 format = None
26 format = None
27
27
28 __formated_value = None
28 __formated_value = None
29
29
30 ELEMENTNAME = 'Parameter'
30 ELEMENTNAME = 'Parameter'
31
31
32 def __init__(self):
32 def __init__(self):
33
33
34 self.format = 'str'
34 self.format = 'str'
35
35
36 def getElementName(self):
36 def getElementName(self):
37
37
38 return self.ELEMENTNAME
38 return self.ELEMENTNAME
39
39
40 def getValue(self):
40 def getValue(self):
41
41
42 if self.__formated_value != None:
42 if self.__formated_value != None:
43
43
44 return self.__formated_value
44 return self.__formated_value
45
45
46 value = self.value
46 value = self.value
47
47
48 if self.format == 'bool':
48 if self.format == 'bool':
49 value = int(value)
49 value = int(value)
50
50
51 if self.format == 'list':
51 if self.format == 'list':
52 strList = value.split(',')
52 strList = value.split(',')
53
53
54 self.__formated_value = strList
54 self.__formated_value = strList
55
55
56 return self.__formated_value
56 return self.__formated_value
57
57
58 if self.format == 'intlist':
58 if self.format == 'intlist':
59 """
59 """
60 Example:
60 Example:
61 value = (0,1,2)
61 value = (0,1,2)
62 """
62 """
63 strList = value.split(',')
63 strList = value.split(',')
64 intList = [int(x) for x in strList]
64 intList = [int(x) for x in strList]
65
65
66 self.__formated_value = intList
66 self.__formated_value = intList
67
67
68 return self.__formated_value
68 return self.__formated_value
69
69
70 if self.format == 'floatlist':
70 if self.format == 'floatlist':
71 """
71 """
72 Example:
72 Example:
73 value = (0.5, 1.4, 2.7)
73 value = (0.5, 1.4, 2.7)
74 """
74 """
75 strList = value.split(',')
75 strList = value.split(',')
76 floatList = [float(x) for x in strList]
76 floatList = [float(x) for x in strList]
77
77
78 self.__formated_value = floatList
78 self.__formated_value = floatList
79
79
80 return self.__formated_value
80 return self.__formated_value
81
81
82 if self.format == 'date':
82 if self.format == 'date':
83 strList = value.split('/')
83 strList = value.split('/')
84 intList = [int(x) for x in strList]
84 intList = [int(x) for x in strList]
85 date = datetime.date(intList[0], intList[1], intList[2])
85 date = datetime.date(intList[0], intList[1], intList[2])
86
86
87 self.__formated_value = date
87 self.__formated_value = date
88
88
89 return self.__formated_value
89 return self.__formated_value
90
90
91 if self.format == 'time':
91 if self.format == 'time':
92 strList = value.split(':')
92 strList = value.split(':')
93 intList = [int(x) for x in strList]
93 intList = [int(x) for x in strList]
94 time = datetime.time(intList[0], intList[1], intList[2])
94 time = datetime.time(intList[0], intList[1], intList[2])
95
95
96 self.__formated_value = time
96 self.__formated_value = time
97
97
98 return self.__formated_value
98 return self.__formated_value
99
99
100 if self.format == 'pairslist':
100 if self.format == 'pairslist':
101 """
101 """
102 Example:
102 Example:
103 value = (0,1),(1,2)
103 value = (0,1),(1,2)
104 """
104 """
105
105
106 value = value.replace('(', '')
106 value = value.replace('(', '')
107 value = value.replace(')', '')
107 value = value.replace(')', '')
108
108
109 strList = value.split(',')
109 strList = value.split(',')
110 intList = [int(item) for item in strList]
110 intList = [int(item) for item in strList]
111 pairList = []
111 pairList = []
112 for i in range(len(intList)/2):
112 for i in range(len(intList)/2):
113 pairList.append((intList[i*2], intList[i*2 + 1]))
113 pairList.append((intList[i*2], intList[i*2 + 1]))
114
114
115 self.__formated_value = pairList
115 self.__formated_value = pairList
116
116
117 return self.__formated_value
117 return self.__formated_value
118
118
119 if self.format == 'multilist':
119 if self.format == 'multilist':
120 """
120 """
121 Example:
121 Example:
122 value = (0,1,2),(3,4,5)
122 value = (0,1,2),(3,4,5)
123 """
123 """
124 multiList = ast.literal_eval(value)
124 multiList = ast.literal_eval(value)
125
125
126 self.__formated_value = multiList
126 self.__formated_value = multiList
127
127
128 return self.__formated_value
128 return self.__formated_value
129
129
130 format_func = eval(self.format)
130 format_func = eval(self.format)
131
131
132 self.__formated_value = format_func(value)
132 self.__formated_value = format_func(value)
133
133
134 return self.__formated_value
134 return self.__formated_value
135
135
136 def setup(self, id, name, value, format='str'):
136 def setup(self, id, name, value, format='str'):
137
137
138 self.id = id
138 self.id = id
139 self.name = name
139 self.name = name
140 self.value = str(value)
140 self.value = str(value)
141 self.format = str.lower(format)
141 self.format = str.lower(format)
142
142
143 def makeXml(self, opElement):
143 def makeXml(self, opElement):
144
144
145 parmElement = SubElement(opElement, self.ELEMENTNAME)
145 parmElement = SubElement(opElement, self.ELEMENTNAME)
146 parmElement.set('id', str(self.id))
146 parmElement.set('id', str(self.id))
147 parmElement.set('name', self.name)
147 parmElement.set('name', self.name)
148 parmElement.set('value', self.value)
148 parmElement.set('value', self.value)
149 parmElement.set('format', self.format)
149 parmElement.set('format', self.format)
150
150
151 def readXml(self, parmElement):
151 def readXml(self, parmElement):
152
152
153 self.id = parmElement.get('id')
153 self.id = parmElement.get('id')
154 self.name = parmElement.get('name')
154 self.name = parmElement.get('name')
155 self.value = parmElement.get('value')
155 self.value = parmElement.get('value')
156 self.format = str.lower(parmElement.get('format'))
156 self.format = str.lower(parmElement.get('format'))
157
157
158 #Compatible with old signal chain version
158 #Compatible with old signal chain version
159 if self.format == 'int' and self.name == 'idfigure':
159 if self.format == 'int' and self.name == 'idfigure':
160 self.name = 'id'
160 self.name = 'id'
161
161
162 def printattr(self):
162 def printattr(self):
163
163
164 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
164 print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format)
165
165
166 class OperationConf():
166 class OperationConf():
167
167
168 id = None
168 id = None
169 name = None
169 name = None
170 priority = None
170 priority = None
171 type = None
171 type = None
172
172
173 parmConfObjList = []
173 parmConfObjList = []
174
174
175 ELEMENTNAME = 'Operation'
175 ELEMENTNAME = 'Operation'
176
176
177 def __init__(self):
177 def __init__(self):
178
178
179 self.id = 0
179 self.id = 0
180 self.name = None
180 self.name = None
181 self.priority = None
181 self.priority = None
182 self.type = 'self'
182 self.type = 'self'
183
183
184
184
185 def __getNewId(self):
185 def __getNewId(self):
186
186
187 return int(self.id)*10 + len(self.parmConfObjList) + 1
187 return int(self.id)*10 + len(self.parmConfObjList) + 1
188
188
189 def getElementName(self):
189 def getElementName(self):
190
190
191 return self.ELEMENTNAME
191 return self.ELEMENTNAME
192
192
193 def getParameterObjList(self):
193 def getParameterObjList(self):
194
194
195 return self.parmConfObjList
195 return self.parmConfObjList
196
196
197 def setup(self, id, name, priority, type):
197 def setup(self, id, name, priority, type):
198
198
199 self.id = id
199 self.id = id
200 self.name = name
200 self.name = name
201 self.type = type
201 self.type = type
202 self.priority = priority
202 self.priority = priority
203
203
204 self.parmConfObjList = []
204 self.parmConfObjList = []
205
205
206 def addParameter(self, name, value, format='str'):
206 def addParameter(self, name, value, format='str'):
207
207
208 id = self.__getNewId()
208 id = self.__getNewId()
209
209
210 parmConfObj = ParameterConf()
210 parmConfObj = ParameterConf()
211 parmConfObj.setup(id, name, value, format)
211 parmConfObj.setup(id, name, value, format)
212
212
213 self.parmConfObjList.append(parmConfObj)
213 self.parmConfObjList.append(parmConfObj)
214
214
215 return parmConfObj
215 return parmConfObj
216
216
217 def makeXml(self, upElement):
217 def makeXml(self, upElement):
218
218
219 opElement = SubElement(upElement, self.ELEMENTNAME)
219 opElement = SubElement(upElement, self.ELEMENTNAME)
220 opElement.set('id', str(self.id))
220 opElement.set('id', str(self.id))
221 opElement.set('name', self.name)
221 opElement.set('name', self.name)
222 opElement.set('type', self.type)
222 opElement.set('type', self.type)
223 opElement.set('priority', str(self.priority))
223 opElement.set('priority', str(self.priority))
224
224
225 for parmConfObj in self.parmConfObjList:
225 for parmConfObj in self.parmConfObjList:
226 parmConfObj.makeXml(opElement)
226 parmConfObj.makeXml(opElement)
227
227
228 def readXml(self, opElement):
228 def readXml(self, opElement):
229
229
230 self.id = opElement.get('id')
230 self.id = opElement.get('id')
231 self.name = opElement.get('name')
231 self.name = opElement.get('name')
232 self.type = opElement.get('type')
232 self.type = opElement.get('type')
233 self.priority = opElement.get('priority')
233 self.priority = opElement.get('priority')
234
234
235 #Compatible with old signal chain version
235 #Compatible with old signal chain version
236 #Use of 'run' method instead 'init'
236 #Use of 'run' method instead 'init'
237 if self.type == 'self' and self.name == 'init':
237 if self.type == 'self' and self.name == 'init':
238 self.name = 'run'
238 self.name = 'run'
239
239
240 self.parmConfObjList = []
240 self.parmConfObjList = []
241
241
242 parmElementList = opElement.getiterator(ParameterConf().getElementName())
242 parmElementList = opElement.getiterator(ParameterConf().getElementName())
243
243
244 for parmElement in parmElementList:
244 for parmElement in parmElementList:
245 parmConfObj = ParameterConf()
245 parmConfObj = ParameterConf()
246 parmConfObj.readXml(parmElement)
246 parmConfObj.readXml(parmElement)
247
247
248 #Compatible with old signal chain version
248 #Compatible with old signal chain version
249 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
249 #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER
250 if self.type != 'self' and self.name == 'Plot':
250 if self.type != 'self' and self.name == 'Plot':
251 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
251 if parmConfObj.format == 'str' and parmConfObj.name == 'type':
252 self.name = parmConfObj.value
252 self.name = parmConfObj.value
253 continue
253 continue
254
254
255 self.parmConfObjList.append(parmConfObj)
255 self.parmConfObjList.append(parmConfObj)
256
256
257 def printattr(self):
257 def printattr(self):
258
258
259 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
259 print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME,
260 self.id,
260 self.id,
261 self.name,
261 self.name,
262 self.type,
262 self.type,
263 self.priority)
263 self.priority)
264
264
265 for parmConfObj in self.parmConfObjList:
265 for parmConfObj in self.parmConfObjList:
266 parmConfObj.printattr()
266 parmConfObj.printattr()
267
267
268 def createObject(self):
268 def createObject(self):
269
269
270 if self.type == 'self':
270 if self.type == 'self':
271 raise ValueError, "This operation type cannot be created"
271 raise ValueError, "This operation type cannot be created"
272
272
273 if self.type == 'external' or self.type == 'other':
273 if self.type == 'external' or self.type == 'other':
274 className = eval(self.name)
274 className = eval(self.name)
275 opObj = className()
275 opObj = className()
276
276
277 return opObj
277 return opObj
278
278
279 class ProcUnitConf():
279 class ProcUnitConf():
280
280
281 id = None
281 id = None
282 name = None
282 name = None
283 datatype = None
283 datatype = None
284 inputId = None
284 inputId = None
285
285
286 opConfObjList = []
286 opConfObjList = []
287
287
288 procUnitObj = None
288 procUnitObj = None
289 opObjList = []
289 opObjList = []
290
290
291 ELEMENTNAME = 'ProcUnit'
291 ELEMENTNAME = 'ProcUnit'
292
292
293 def __init__(self):
293 def __init__(self):
294
294
295 self.id = None
295 self.id = None
296 self.datatype = None
296 self.datatype = None
297 self.name = None
297 self.name = None
298 self.inputId = None
298 self.inputId = None
299
299
300 self.opConfObjList = []
300 self.opConfObjList = []
301
301
302 self.procUnitObj = None
302 self.procUnitObj = None
303 self.opObjDict = {}
303 self.opObjDict = {}
304
304
305 def __getPriority(self):
305 def __getPriority(self):
306
306
307 return len(self.opConfObjList)+1
307 return len(self.opConfObjList)+1
308
308
309 def __getNewId(self):
309 def __getNewId(self):
310
310
311 return int(self.id)*10 + len(self.opConfObjList) + 1
311 return int(self.id)*10 + len(self.opConfObjList) + 1
312
312
313 def getElementName(self):
313 def getElementName(self):
314
314
315 return self.ELEMENTNAME
315 return self.ELEMENTNAME
316
316
317 def getId(self):
317 def getId(self):
318
318
319 return str(self.id)
319 return str(self.id)
320
320
321 def getInputId(self):
321 def getInputId(self):
322
322
323 return str(self.inputId)
323 return str(self.inputId)
324
324
325 def getOperationObjList(self):
325 def getOperationObjList(self):
326
326
327 return self.opConfObjList
327 return self.opConfObjList
328
328
329 def getProcUnitObj(self):
329 def getProcUnitObj(self):
330
330
331 return self.procUnitObj
331 return self.procUnitObj
332
332
333 def setup(self, id, name, datatype, inputId):
333 def setup(self, id, name, datatype, inputId):
334
334
335 self.id = id
335 self.id = id
336 self.name = name
336 self.name = name
337 self.datatype = datatype
337 self.datatype = datatype
338 self.inputId = inputId
338 self.inputId = inputId
339
339
340 self.opConfObjList = []
340 self.opConfObjList = []
341
341
342 self.addOperation(name='run', optype='self')
342 self.addOperation(name='run', optype='self')
343
343
344 def addParameter(self, **kwargs):
344 def addParameter(self, **kwargs):
345
345
346 opObj = self.opConfObjList[0]
346 opObj = self.opConfObjList[0]
347
347
348 opObj.addParameter(**kwargs)
348 opObj.addParameter(**kwargs)
349
349
350 return opObj
350 return opObj
351
351
352 def addOperation(self, name, optype='self'):
352 def addOperation(self, name, optype='self'):
353
353
354 id = self.__getNewId()
354 id = self.__getNewId()
355 priority = self.__getPriority()
355 priority = self.__getPriority()
356
356
357 opConfObj = OperationConf()
357 opConfObj = OperationConf()
358 opConfObj.setup(id, name=name, priority=priority, type=optype)
358 opConfObj.setup(id, name=name, priority=priority, type=optype)
359
359
360 self.opConfObjList.append(opConfObj)
360 self.opConfObjList.append(opConfObj)
361
361
362 return opConfObj
362 return opConfObj
363
363
364 def makeXml(self, procUnitElement):
364 def makeXml(self, procUnitElement):
365
365
366 upElement = SubElement(procUnitElement, self.ELEMENTNAME)
366 upElement = SubElement(procUnitElement, self.ELEMENTNAME)
367 upElement.set('id', str(self.id))
367 upElement.set('id', str(self.id))
368 upElement.set('name', self.name)
368 upElement.set('name', self.name)
369 upElement.set('datatype', self.datatype)
369 upElement.set('datatype', self.datatype)
370 upElement.set('inputId', str(self.inputId))
370 upElement.set('inputId', str(self.inputId))
371
371
372 for opConfObj in self.opConfObjList:
372 for opConfObj in self.opConfObjList:
373 opConfObj.makeXml(upElement)
373 opConfObj.makeXml(upElement)
374
374
375 def readXml(self, upElement):
375 def readXml(self, upElement):
376
376
377 self.id = upElement.get('id')
377 self.id = upElement.get('id')
378 self.name = upElement.get('name')
378 self.name = upElement.get('name')
379 self.datatype = upElement.get('datatype')
379 self.datatype = upElement.get('datatype')
380 self.inputId = upElement.get('inputId')
380 self.inputId = upElement.get('inputId')
381
382 #Compatible with old signal chain version
383 if self.ELEMENTNAME == ReadUnitConf().getElementName():
384 if 'Reader' not in self.name:
385 self.name += 'Reader'
386
387 if self.ELEMENTNAME == ProcUnitConf().getElementName():
388 if 'Proc' not in self.name:
389 self.name += 'Proc'
390
381
391 self.opConfObjList = []
382 self.opConfObjList = []
392
383
393 opElementList = upElement.getiterator(OperationConf().getElementName())
384 opElementList = upElement.getiterator(OperationConf().getElementName())
394
385
395 for opElement in opElementList:
386 for opElement in opElementList:
396 opConfObj = OperationConf()
387 opConfObj = OperationConf()
397 opConfObj.readXml(opElement)
388 opConfObj.readXml(opElement)
398 self.opConfObjList.append(opConfObj)
389 self.opConfObjList.append(opConfObj)
399
390
400 def printattr(self):
391 def printattr(self):
401
392
402 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
393 print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME,
403 self.id,
394 self.id,
404 self.name,
395 self.name,
405 self.datatype,
396 self.datatype,
406 self.inputId)
397 self.inputId)
407
398
408 for opConfObj in self.opConfObjList:
399 for opConfObj in self.opConfObjList:
409 opConfObj.printattr()
400 opConfObj.printattr()
410
401
411 def createObjects(self):
402 def createObjects(self):
412
403
413 className = eval(self.name)
404 className = eval(self.name)
414 procUnitObj = className()
405 procUnitObj = className()
415
406
416 for opConfObj in self.opConfObjList:
407 for opConfObj in self.opConfObjList:
417
408
418 if opConfObj.type == 'self':
409 if opConfObj.type == 'self':
419 continue
410 continue
420
411
421 opObj = opConfObj.createObject()
412 opObj = opConfObj.createObject()
422
413
423 self.opObjDict[opConfObj.id] = opObj
414 self.opObjDict[opConfObj.id] = opObj
424 procUnitObj.addOperation(opObj, opConfObj.id)
415 procUnitObj.addOperation(opObj, opConfObj.id)
425
416
426 self.procUnitObj = procUnitObj
417 self.procUnitObj = procUnitObj
427
418
428 return procUnitObj
419 return procUnitObj
429
420
430 def run(self):
421 def run(self):
431
422
432 finalSts = False
423 finalSts = False
433
424
434 for opConfObj in self.opConfObjList:
425 for opConfObj in self.opConfObjList:
435
426
436 kwargs = {}
427 kwargs = {}
437 for parmConfObj in opConfObj.getParameterObjList():
428 for parmConfObj in opConfObj.getParameterObjList():
438 kwargs[parmConfObj.name] = parmConfObj.getValue()
429 kwargs[parmConfObj.name] = parmConfObj.getValue()
439
430
440 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
431 #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id)
441 sts = self.procUnitObj.call(opType = opConfObj.type,
432 sts = self.procUnitObj.call(opType = opConfObj.type,
442 opName = opConfObj.name,
433 opName = opConfObj.name,
443 opId = opConfObj.id,
434 opId = opConfObj.id,
444 **kwargs)
435 **kwargs)
445 finalSts = finalSts or sts
436 finalSts = finalSts or sts
446
437
447 return finalSts
438 return finalSts
448
439
440 def close(self):
441
442 self.procUnitObj.close()
443
444 return
445
449 class ReadUnitConf(ProcUnitConf):
446 class ReadUnitConf(ProcUnitConf):
450
447
451 path = None
448 path = None
452 startDate = None
449 startDate = None
453 endDate = None
450 endDate = None
454 startTime = None
451 startTime = None
455 endTime = None
452 endTime = None
456
453
457 ELEMENTNAME = 'ReadUnit'
454 ELEMENTNAME = 'ReadUnit'
458
455
459 def __init__(self):
456 def __init__(self):
460
457
461 self.id = None
458 self.id = None
462 self.datatype = None
459 self.datatype = None
463 self.name = None
460 self.name = None
464 self.inputId = 0
461 self.inputId = 0
465
462
466 self.opConfObjList = []
463 self.opConfObjList = []
467 self.opObjList = []
464 self.opObjList = []
468
465
469 def getElementName(self):
466 def getElementName(self):
470
467
471 return self.ELEMENTNAME
468 return self.ELEMENTNAME
472
469
473 def setup(self, id, name, datatype, path="", startDate="", endDate="", startTime="", endTime="", **kwargs):
470 def setup(self, id, name, datatype, path="", startDate="", endDate="", startTime="", endTime="", **kwargs):
474
471
475 self.id = id
472 self.id = id
476 self.name = name
473 self.name = name
477 self.datatype = datatype
474 self.datatype = datatype
478
475
479 self.path = path
476 self.path = path
480 self.startDate = startDate
477 self.startDate = startDate
481 self.endDate = endDate
478 self.endDate = endDate
482 self.startTime = startTime
479 self.startTime = startTime
483 self.endTime = endTime
480 self.endTime = endTime
484
481
485 self.addRunOperation(**kwargs)
482 self.addRunOperation(**kwargs)
486
483
487 def addRunOperation(self, **kwargs):
484 def addRunOperation(self, **kwargs):
488
485
489 opObj = self.addOperation(name = 'run', optype = 'self')
486 opObj = self.addOperation(name = 'run', optype = 'self')
490
487
491 opObj.addParameter(name='path' , value=self.path, format='str')
488 opObj.addParameter(name='path' , value=self.path, format='str')
492 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
489 opObj.addParameter(name='startDate' , value=self.startDate, format='date')
493 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
490 opObj.addParameter(name='endDate' , value=self.endDate, format='date')
494 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
491 opObj.addParameter(name='startTime' , value=self.startTime, format='time')
495 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
492 opObj.addParameter(name='endTime' , value=self.endTime, format='time')
496
493
497 for key, value in kwargs.items():
494 for key, value in kwargs.items():
498 opObj.addParameter(name=key, value=value, format=type(value).__name__)
495 opObj.addParameter(name=key, value=value, format=type(value).__name__)
499
496
500 return opObj
497 return opObj
501
498
502
499
503 class Project():
500 class Project():
504
501
505 id = None
502 id = None
506 name = None
503 name = None
507 description = None
504 description = None
508 # readUnitConfObjList = None
505 # readUnitConfObjList = None
509 procUnitConfObjDict = None
506 procUnitConfObjDict = None
510
507
511 ELEMENTNAME = 'Project'
508 ELEMENTNAME = 'Project'
512
509
513 def __init__(self):
510 def __init__(self):
514
511
515 self.id = None
512 self.id = None
516 self.name = None
513 self.name = None
517 self.description = None
514 self.description = None
518
515
519 # self.readUnitConfObjList = []
516 # self.readUnitConfObjList = []
520 self.procUnitConfObjDict = {}
517 self.procUnitConfObjDict = {}
521
518
522 def __getNewId(self):
519 def __getNewId(self):
523
520
524 id = int(self.id)*10 + len(self.procUnitConfObjDict) + 1
521 id = int(self.id)*10 + len(self.procUnitConfObjDict) + 1
525
522
526 return str(id)
523 return str(id)
527
524
528 def getElementName(self):
525 def getElementName(self):
529
526
530 return self.ELEMENTNAME
527 return self.ELEMENTNAME
531
528
532 def setup(self, id, name, description):
529 def setup(self, id, name, description):
533
530
534 self.id = id
531 self.id = id
535 self.name = name
532 self.name = name
536 self.description = description
533 self.description = description
537
534
538 def addReadUnit(self, datatype=None, name=None, **kwargs):
535 def addReadUnit(self, datatype=None, name=None, **kwargs):
539
536
540 #Compatible with old signal chain version
537 #Compatible with old signal chain version
541 if datatype==None and name==None:
538 if datatype==None and name==None:
542 raise ValueError, "datatype or name should be defined"
539 raise ValueError, "datatype or name should be defined"
543
540
544 if name==None:
541 if name==None:
545 if 'Reader' in datatype:
542 if 'Reader' in datatype:
546 name = datatype
543 name = datatype
547 else:
544 else:
548 name = '%sReader' %(datatype)
545 name = '%sReader' %(datatype)
549
546
550 if datatype==None:
547 if datatype==None:
551 datatype = name.replace('Reader','')
548 datatype = name.replace('Reader','')
552
549
553 id = self.__getNewId()
550 id = self.__getNewId()
554
551
555 readUnitConfObj = ReadUnitConf()
552 readUnitConfObj = ReadUnitConf()
556 readUnitConfObj.setup(id, name, datatype, **kwargs)
553 readUnitConfObj.setup(id, name, datatype, **kwargs)
557
554
558 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
555 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
559
556
560 return readUnitConfObj
557 return readUnitConfObj
561
558
562 def addProcUnit(self, inputId, datatype=None, name=None):
559 def addProcUnit(self, inputId=0, datatype=None, name=None):
563
560
564 #Compatible with old signal chain version
561 #Compatible with old signal chain version
565 if datatype==None and name==None:
562 if datatype==None and name==None:
566 raise ValueError, "datatype or name should be defined"
563 raise ValueError, "datatype or name should be defined"
567
564
568 if name==None:
565 if name==None:
569 if 'Proc' in datatype:
566 if 'Proc' in datatype:
570 name = datatype
567 name = datatype
571 else:
568 else:
572 name = '%sProc' %(datatype)
569 name = '%sProc' %(datatype)
573
570
574 if datatype==None:
571 if datatype==None:
575 datatype = name.replace('Proc','')
572 datatype = name.replace('Proc','')
576
573
577 id = self.__getNewId()
574 id = self.__getNewId()
578
575
579 procUnitConfObj = ProcUnitConf()
576 procUnitConfObj = ProcUnitConf()
580 procUnitConfObj.setup(id, name, datatype, inputId)
577 procUnitConfObj.setup(id, name, datatype, inputId)
581
578
582 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
579 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
583
580
584 return procUnitConfObj
581 return procUnitConfObj
585
582
586 def makeXml(self):
583 def makeXml(self):
587
584
588 projectElement = Element('Project')
585 projectElement = Element('Project')
589 projectElement.set('id', str(self.id))
586 projectElement.set('id', str(self.id))
590 projectElement.set('name', self.name)
587 projectElement.set('name', self.name)
591 projectElement.set('description', self.description)
588 projectElement.set('description', self.description)
592
589
593 # for readUnitConfObj in self.readUnitConfObjList:
590 # for readUnitConfObj in self.readUnitConfObjList:
594 # readUnitConfObj.makeXml(projectElement)
591 # readUnitConfObj.makeXml(projectElement)
595
592
596 for procUnitConfObj in self.procUnitConfObjDict.values():
593 for procUnitConfObj in self.procUnitConfObjDict.values():
597 procUnitConfObj.makeXml(projectElement)
594 procUnitConfObj.makeXml(projectElement)
598
595
599 self.projectElement = projectElement
596 self.projectElement = projectElement
600
597
601 def writeXml(self, filename):
598 def writeXml(self, filename):
602
599
603 self.makeXml()
600 self.makeXml()
604
601
605 #print prettify(self.projectElement)
602 #print prettify(self.projectElement)
606
603
607 ElementTree(self.projectElement).write(filename, method='xml')
604 ElementTree(self.projectElement).write(filename, method='xml')
608
605
609 def readXml(self, filename):
606 def readXml(self, filename):
610
607
611 #tree = ET.parse(filename)
608 #tree = ET.parse(filename)
612 self.projectElement = None
609 self.projectElement = None
613 # self.readUnitConfObjList = []
610 # self.readUnitConfObjList = []
614 self.procUnitConfObjDict = {}
611 self.procUnitConfObjDict = {}
615
612
616 self.projectElement = ElementTree().parse(filename)
613 self.projectElement = ElementTree().parse(filename)
617
614
618 self.project = self.projectElement.tag
615 self.project = self.projectElement.tag
619
616
620 self.id = self.projectElement.get('id')
617 self.id = self.projectElement.get('id')
621 self.name = self.projectElement.get('name')
618 self.name = self.projectElement.get('name')
622 self.description = self.projectElement.get('description')
619 self.description = self.projectElement.get('description')
623
620
624 readUnitElementList = self.projectElement.getiterator(ReadUnitConf().getElementName())
621 readUnitElementList = self.projectElement.getiterator(ReadUnitConf().getElementName())
625
622
626 for readUnitElement in readUnitElementList:
623 for readUnitElement in readUnitElementList:
627 readUnitConfObj = ReadUnitConf()
624 readUnitConfObj = ReadUnitConf()
628 readUnitConfObj.readXml(readUnitElement)
625 readUnitConfObj.readXml(readUnitElement)
629
626
630 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
627 self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj
631
628
632 procUnitElementList = self.projectElement.getiterator(ProcUnitConf().getElementName())
629 procUnitElementList = self.projectElement.getiterator(ProcUnitConf().getElementName())
633
630
634 for procUnitElement in procUnitElementList:
631 for procUnitElement in procUnitElementList:
635 procUnitConfObj = ProcUnitConf()
632 procUnitConfObj = ProcUnitConf()
636 procUnitConfObj.readXml(procUnitElement)
633 procUnitConfObj.readXml(procUnitElement)
637
634
638 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
635 self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj
639
636
640 def printattr(self):
637 def printattr(self):
641
638
642 print "Project[%s]: name = %s, description = %s" %(self.id,
639 print "Project[%s]: name = %s, description = %s" %(self.id,
643 self.name,
640 self.name,
644 self.description)
641 self.description)
645
642
646 # for readUnitConfObj in self.readUnitConfObjList:
643 # for readUnitConfObj in self.readUnitConfObjList:
647 # readUnitConfObj.printattr()
644 # readUnitConfObj.printattr()
648
645
649 for procUnitConfObj in self.procUnitConfObjDict.values():
646 for procUnitConfObj in self.procUnitConfObjDict.values():
650 procUnitConfObj.printattr()
647 procUnitConfObj.printattr()
651
648
652 def createObjects(self):
649 def createObjects(self):
653
650
654 # for readUnitConfObj in self.readUnitConfObjList:
651 # for readUnitConfObj in self.readUnitConfObjList:
655 # readUnitConfObj.createObjects()
652 # readUnitConfObj.createObjects()
656
653
657 for procUnitConfObj in self.procUnitConfObjDict.values():
654 for procUnitConfObj in self.procUnitConfObjDict.values():
658 procUnitConfObj.createObjects()
655 procUnitConfObj.createObjects()
659
656
660 def __connect(self, objIN, thisObj):
657 def __connect(self, objIN, thisObj):
661
658
662 thisObj.setInput(objIN.getOutputObj())
659 thisObj.setInput(objIN.getOutputObj())
663
660
664 def connectObjects(self):
661 def connectObjects(self):
665
662
666 for thisPUConfObj in self.procUnitConfObjDict.values():
663 for thisPUConfObj in self.procUnitConfObjDict.values():
667
664
668 inputId = thisPUConfObj.getInputId()
665 inputId = thisPUConfObj.getInputId()
669
666
670 if int(inputId) == 0:
667 if int(inputId) == 0:
671 continue
668 continue
672
669
673 #Get input object
670 #Get input object
674 puConfINObj = self.procUnitConfObjDict[inputId]
671 puConfINObj = self.procUnitConfObjDict[inputId]
675 puObjIN = puConfINObj.getProcUnitObj()
672 puObjIN = puConfINObj.getProcUnitObj()
676
673
677 #Get current object
674 #Get current object
678 thisPUObj = thisPUConfObj.getProcUnitObj()
675 thisPUObj = thisPUConfObj.getProcUnitObj()
679
676
680 self.__connect(puObjIN, thisPUObj)
677 self.__connect(puObjIN, thisPUObj)
681
678
682 def run(self):
679 def run(self):
683
680
684 # for readUnitConfObj in self.readUnitConfObjList:
681 # for readUnitConfObj in self.readUnitConfObjList:
685 # readUnitConfObj.run()
682 # readUnitConfObj.run()
686 print
683 print
687 print "*"*40
684 print "*"*40
688 print " Starting SIGNAL CHAIN PROCESSING "
685 print " Starting SIGNAL CHAIN PROCESSING "
689 print "*"*40
686 print "*"*40
690 print
687 print
691
688
692 keyList = self.procUnitConfObjDict.keys()
689 keyList = self.procUnitConfObjDict.keys()
693 keyList.sort()
690 keyList.sort()
694
691
695 while(True):
692 while(True):
696
693
697 finalSts = False
694 finalSts = False
698
695
699 for procKey in keyList:
696 for procKey in keyList:
700 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
697 # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id)
701
698
702 procUnitConfObj = self.procUnitConfObjDict[procKey]
699 procUnitConfObj = self.procUnitConfObjDict[procKey]
703 sts = procUnitConfObj.run()
700 sts = procUnitConfObj.run()
704 finalSts = finalSts or sts
701 finalSts = finalSts or sts
705
702
706 #If every process unit finished so end process
703 #If every process unit finished so end process
707 if not(finalSts):
704 if not(finalSts):
708 print "Every process unit have finished"
705 print "Every process unit have finished"
709 break
706 break
710
707
708 #Closing every process
709 for procKey in keyList:
710 procUnitConfObj = self.procUnitConfObjDict[procKey]
711 procUnitConfObj.close()
712
713 def start(self, filename):
714
715 self.writeXml(filename)
716 self.readXml(filename)
717
718 self.createObjects()
719 self.connectObjects()
720 self.run()
721
711 if __name__ == '__main__':
722 if __name__ == '__main__':
712
723
713 desc = "Segundo Test"
724 desc = "Segundo Test"
714 filename = "schain.xml"
725 filename = "schain.xml"
715
726
716 controllerObj = Project()
727 controllerObj = Project()
717
728
718 controllerObj.setup(id = '191', name='test01', description=desc)
729 controllerObj.setup(id = '191', name='test01', description=desc)
719
730
720 readUnitConfObj = controllerObj.addReadUnit(datatype='Voltage',
731 readUnitConfObj = controllerObj.addReadUnit(datatype='Voltage',
721 path='data/rawdata/',
732 path='data/rawdata/',
722 startDate='2011/01/01',
733 startDate='2011/01/01',
723 endDate='2012/12/31',
734 endDate='2012/12/31',
724 startTime='00:00:00',
735 startTime='00:00:00',
725 endTime='23:59:59',
736 endTime='23:59:59',
726 online=1,
737 online=1,
727 walk=1)
738 walk=1)
728
739
729 # opObj00 = readUnitConfObj.addOperation(name='printInfo')
740 # opObj00 = readUnitConfObj.addOperation(name='printInfo')
730
741
731 procUnitConfObj0 = controllerObj.addProcUnit(datatype='Voltage', inputId=readUnitConfObj.getId())
742 procUnitConfObj0 = controllerObj.addProcUnit(datatype='Voltage', inputId=readUnitConfObj.getId())
732
743
733 opObj10 = procUnitConfObj0.addOperation(name='selectChannels')
744 opObj10 = procUnitConfObj0.addOperation(name='selectChannels')
734 opObj10.addParameter(name='channelList', value='3,4,5', format='intlist')
745 opObj10.addParameter(name='channelList', value='3,4,5', format='intlist')
735
746
736 opObj10 = procUnitConfObj0.addOperation(name='selectHeights')
747 opObj10 = procUnitConfObj0.addOperation(name='selectHeights')
737 opObj10.addParameter(name='minHei', value='90', format='float')
748 opObj10.addParameter(name='minHei', value='90', format='float')
738 opObj10.addParameter(name='maxHei', value='180', format='float')
749 opObj10.addParameter(name='maxHei', value='180', format='float')
739
750
740 opObj12 = procUnitConfObj0.addOperation(name='CohInt', optype='external')
751 opObj12 = procUnitConfObj0.addOperation(name='CohInt', optype='external')
741 opObj12.addParameter(name='n', value='10', format='int')
752 opObj12.addParameter(name='n', value='10', format='int')
742
753
743 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj0.getId())
754 procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj0.getId())
744 procUnitConfObj1.addParameter(name='nFFTPoints', value='32', format='int')
755 procUnitConfObj1.addParameter(name='nFFTPoints', value='32', format='int')
745 # procUnitConfObj1.addParameter(name='pairList', value='(0,1),(0,2),(1,2)', format='')
756 # procUnitConfObj1.addParameter(name='pairList', value='(0,1),(0,2),(1,2)', format='')
746
757
747
758
748 opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
759 opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
749 opObj11.addParameter(name='idfigure', value='1', format='int')
760 opObj11.addParameter(name='idfigure', value='1', format='int')
750 opObj11.addParameter(name='wintitle', value='SpectraPlot0', format='str')
761 opObj11.addParameter(name='wintitle', value='SpectraPlot0', format='str')
751 opObj11.addParameter(name='zmin', value='40', format='int')
762 opObj11.addParameter(name='zmin', value='40', format='int')
752 opObj11.addParameter(name='zmax', value='90', format='int')
763 opObj11.addParameter(name='zmax', value='90', format='int')
753 opObj11.addParameter(name='showprofile', value='1', format='int')
764 opObj11.addParameter(name='showprofile', value='1', format='int')
754
765
755 # opObj11 = procUnitConfObj1.addOperation(name='CrossSpectraPlot', optype='external')
766 # opObj11 = procUnitConfObj1.addOperation(name='CrossSpectraPlot', optype='external')
756 # opObj11.addParameter(name='idfigure', value='2', format='int')
767 # opObj11.addParameter(name='idfigure', value='2', format='int')
757 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
768 # opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str')
758 # opObj11.addParameter(name='zmin', value='40', format='int')
769 # opObj11.addParameter(name='zmin', value='40', format='int')
759 # opObj11.addParameter(name='zmax', value='90', format='int')
770 # opObj11.addParameter(name='zmax', value='90', format='int')
760
771
761
772
762 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Voltage', inputId=procUnitConfObj0.getId())
773 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Voltage', inputId=procUnitConfObj0.getId())
763 #
774 #
764 # opObj12 = procUnitConfObj2.addOperation(name='CohInt', optype='external')
775 # opObj12 = procUnitConfObj2.addOperation(name='CohInt', optype='external')
765 # opObj12.addParameter(name='n', value='2', format='int')
776 # opObj12.addParameter(name='n', value='2', format='int')
766 # opObj12.addParameter(name='overlapping', value='1', format='int')
777 # opObj12.addParameter(name='overlapping', value='1', format='int')
767 #
778 #
768 # procUnitConfObj3 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj2.getId())
779 # procUnitConfObj3 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj2.getId())
769 # procUnitConfObj3.addParameter(name='nFFTPoints', value='32', format='int')
780 # procUnitConfObj3.addParameter(name='nFFTPoints', value='32', format='int')
770 #
781 #
771 # opObj11 = procUnitConfObj3.addOperation(name='SpectraPlot', optype='external')
782 # opObj11 = procUnitConfObj3.addOperation(name='SpectraPlot', optype='external')
772 # opObj11.addParameter(name='idfigure', value='2', format='int')
783 # opObj11.addParameter(name='idfigure', value='2', format='int')
773 # opObj11.addParameter(name='wintitle', value='SpectraPlot1', format='str')
784 # opObj11.addParameter(name='wintitle', value='SpectraPlot1', format='str')
774 # opObj11.addParameter(name='zmin', value='40', format='int')
785 # opObj11.addParameter(name='zmin', value='40', format='int')
775 # opObj11.addParameter(name='zmax', value='90', format='int')
786 # opObj11.addParameter(name='zmax', value='90', format='int')
776 # opObj11.addParameter(name='showprofile', value='1', format='int')
787 # opObj11.addParameter(name='showprofile', value='1', format='int')
777
788
778 # opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='external')
789 # opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='external')
779 # opObj11.addParameter(name='idfigure', value='10', format='int')
790 # opObj11.addParameter(name='idfigure', value='10', format='int')
780 # opObj11.addParameter(name='wintitle', value='RTI', format='str')
791 # opObj11.addParameter(name='wintitle', value='RTI', format='str')
781 ## opObj11.addParameter(name='xmin', value='21', format='float')
792 ## opObj11.addParameter(name='xmin', value='21', format='float')
782 ## opObj11.addParameter(name='xmax', value='22', format='float')
793 ## opObj11.addParameter(name='xmax', value='22', format='float')
783 # opObj11.addParameter(name='zmin', value='40', format='int')
794 # opObj11.addParameter(name='zmin', value='40', format='int')
784 # opObj11.addParameter(name='zmax', value='90', format='int')
795 # opObj11.addParameter(name='zmax', value='90', format='int')
785 # opObj11.addParameter(name='showprofile', value='1', format='int')
796 # opObj11.addParameter(name='showprofile', value='1', format='int')
786 # opObj11.addParameter(name='timerange', value=str(60), format='int')
797 # opObj11.addParameter(name='timerange', value=str(60), format='int')
787
798
788 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
799 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
789 # opObj10.addParameter(name='channelList', value='0,2,4,6', format='intlist')
800 # opObj10.addParameter(name='channelList', value='0,2,4,6', format='intlist')
790 #
801 #
791 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
802 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
792 # opObj12.addParameter(name='n', value='2', format='int')
803 # opObj12.addParameter(name='n', value='2', format='int')
793 #
804 #
794 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
805 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
795 # opObj11.addParameter(name='idfigure', value='2', format='int')
806 # opObj11.addParameter(name='idfigure', value='2', format='int')
796 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
807 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
797 # opObj11.addParameter(name='zmin', value='70', format='int')
808 # opObj11.addParameter(name='zmin', value='70', format='int')
798 # opObj11.addParameter(name='zmax', value='90', format='int')
809 # opObj11.addParameter(name='zmax', value='90', format='int')
799 #
810 #
800 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
811 # opObj10 = procUnitConfObj1.addOperation(name='selectChannels')
801 # opObj10.addParameter(name='channelList', value='2,6', format='intlist')
812 # opObj10.addParameter(name='channelList', value='2,6', format='intlist')
802 #
813 #
803 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
814 # opObj12 = procUnitConfObj1.addOperation(name='IncohInt', optype='external')
804 # opObj12.addParameter(name='n', value='2', format='int')
815 # opObj12.addParameter(name='n', value='2', format='int')
805 #
816 #
806 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
817 # opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='external')
807 # opObj11.addParameter(name='idfigure', value='3', format='int')
818 # opObj11.addParameter(name='idfigure', value='3', format='int')
808 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
819 # opObj11.addParameter(name='wintitle', value='SpectraPlot10', format='str')
809 # opObj11.addParameter(name='zmin', value='70', format='int')
820 # opObj11.addParameter(name='zmin', value='70', format='int')
810 # opObj11.addParameter(name='zmax', value='90', format='int')
821 # opObj11.addParameter(name='zmax', value='90', format='int')
811
822
812
823
813 # opObj12 = procUnitConfObj1.addOperation(name='decoder')
824 # opObj12 = procUnitConfObj1.addOperation(name='decoder')
814 # opObj12.addParameter(name='ncode', value='2', format='int')
825 # opObj12.addParameter(name='ncode', value='2', format='int')
815 # opObj12.addParameter(name='nbauds', value='8', format='int')
826 # opObj12.addParameter(name='nbauds', value='8', format='int')
816 # opObj12.addParameter(name='code0', value='001110011', format='int')
827 # opObj12.addParameter(name='code0', value='001110011', format='int')
817 # opObj12.addParameter(name='code1', value='001110011', format='int')
828 # opObj12.addParameter(name='code1', value='001110011', format='int')
818
829
819
830
820
831
821 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj1.getId())
832 # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Spectra', inputId=procUnitConfObj1.getId())
822 #
833 #
823 # opObj21 = procUnitConfObj2.addOperation(name='IncohInt', optype='external')
834 # opObj21 = procUnitConfObj2.addOperation(name='IncohInt', optype='external')
824 # opObj21.addParameter(name='n', value='2', format='int')
835 # opObj21.addParameter(name='n', value='2', format='int')
825 #
836 #
826 # opObj11 = procUnitConfObj2.addOperation(name='SpectraPlot', optype='external')
837 # opObj11 = procUnitConfObj2.addOperation(name='SpectraPlot', optype='external')
827 # opObj11.addParameter(name='idfigure', value='4', format='int')
838 # opObj11.addParameter(name='idfigure', value='4', format='int')
828 # opObj11.addParameter(name='wintitle', value='SpectraPlot OBJ 2', format='str')
839 # opObj11.addParameter(name='wintitle', value='SpectraPlot OBJ 2', format='str')
829 # opObj11.addParameter(name='zmin', value='70', format='int')
840 # opObj11.addParameter(name='zmin', value='70', format='int')
830 # opObj11.addParameter(name='zmax', value='90', format='int')
841 # opObj11.addParameter(name='zmax', value='90', format='int')
831
842
832 print "Escribiendo el archivo XML"
843 print "Escribiendo el archivo XML"
833
844
834 controllerObj.writeXml(filename)
845 controllerObj.writeXml(filename)
835
846
836 print "Leyendo el archivo XML"
847 print "Leyendo el archivo XML"
837 controllerObj.readXml(filename)
848 controllerObj.readXml(filename)
838 #controllerObj.printattr()
849 #controllerObj.printattr()
839
850
840 controllerObj.createObjects()
851 controllerObj.createObjects()
841 controllerObj.connectObjects()
852 controllerObj.connectObjects()
842 controllerObj.run()
853 controllerObj.run()
843
854
844 No newline at end of file
855
@@ -1,608 +1,650
1 import os
1 import os
2 import numpy
2 import numpy
3 import time, datetime
3 import time, datetime
4 import mpldriver
4 import mpldriver
5
5
6
6
7 import Queue
7 import Queue
8 import threading
8 import threading
9
9
10 def isRealtime(utcdatatime):
10 def isRealtime(utcdatatime):
11 utcnow = time.mktime(time.localtime())
11 utcnow = time.mktime(time.localtime())
12 delta = abs(utcnow - utcdatatime) # abs
12 delta = abs(utcnow - utcdatatime) # abs
13 if delta >= 30.:
13 if delta >= 30.:
14 return False
14 return False
15 return True
15 return True
16
16
17
17
18
18
19
19
20 class Figure:
20 class Figure:
21
21
22 __driver = mpldriver
22 __driver = mpldriver
23 __isConfigThread = False
23 __isConfigThread = False
24 fig = None
24 fig = None
25
25
26 id = None
26 id = None
27 wintitle = None
27 wintitle = None
28 width = None
28 width = None
29 height = None
29 height = None
30 nplots = None
30 nplots = None
31 timerange = None
31 timerange = None
32
32
33 axesObjList = []
33 axesObjList = []
34
34
35 WIDTH = None
35 WIDTH = None
36 HEIGHT = None
36 HEIGHT = None
37 PREFIX = 'fig'
37 PREFIX = 'fig'
38
38
39 xmin = None
39 xmin = None
40 xmax = None
40 xmax = None
41
41
42 counter_imagwr = 0
43
44 figfile = None
45
42 def __init__(self):
46 def __init__(self):
43
47
44 raise ValueError, "This method is not implemented"
48 raise ValueError, "This method is not implemented"
45
49
46 def __del__(self):
50 def __del__(self):
47
51
48 self.__driver.closeFigure(True)
52 self.__driver.closeFigure(True)
49
53
50 def getFilename(self, name, ext='.png'):
54 def getFilename(self, name, ext='.png'):
51
55
52 path = '%s%03d' %(self.PREFIX, self.id)
56 path = '%s%03d' %(self.PREFIX, self.id)
53 filename = '%s_%s%s' %(self.PREFIX, name, ext)
57 filename = '%s_%s%s' %(self.PREFIX, name, ext)
54 return os.path.join(path, filename)
58 return os.path.join(path, filename)
55
59
56 def getAxesObjList(self):
60 def getAxesObjList(self):
57
61
58 return self.axesObjList
62 return self.axesObjList
59
63
60 def getSubplots(self):
64 def getSubplots(self):
61
65
62 raise ValueError, "Abstract method: This method should be defined"
66 raise ValueError, "Abstract method: This method should be defined"
63
67
64 def getScreenDim(self, widthplot, heightplot):
68 def getScreenDim(self, widthplot, heightplot):
65
69
66 nrow, ncol = self.getSubplots()
70 nrow, ncol = self.getSubplots()
67
71
68 widthscreen = widthplot*ncol
72 widthscreen = widthplot*ncol
69 heightscreen = heightplot*nrow
73 heightscreen = heightplot*nrow
70
74
71 return widthscreen, heightscreen
75 return widthscreen, heightscreen
72
76
73 def getTimeLim(self, x, xmin=None, xmax=None, timerange=None):
77 def getTimeLim(self, x, xmin=None, xmax=None, timerange=None):
74
78
75 if self.xmin != None and self.xmax != None:
79 if self.xmin != None and self.xmax != None:
76 if timerange == None:
80 if timerange == None:
77 timerange = self.xmax - self.xmin
81 timerange = self.xmax - self.xmin
78 xmin = self.xmin + timerange
82 xmin = self.xmin + timerange
79 xmax = self.xmax + timerange
83 xmax = self.xmax + timerange
80
84
81 return xmin, xmax
85 return xmin, xmax
82
86
83 if timerange == None and (xmin==None or xmax==None):
87 if timerange == None and (xmin==None or xmax==None):
84 raise ValueError, "timerange or xmin+xmax should be defined"
88 raise ValueError, "timerange or xmin+xmax should be defined"
85
89
86 if timerange != None:
90 if timerange != None:
87 txmin = x[0] - x[0] % min(timerange/10, 10*60)
91 txmin = x[0] - x[0] % min(timerange/10, 10*60)
88 else:
92 else:
89 txmin = x[0] - x[0] % 10*60
93 txmin = x[0] - x[0] % 10*60
90
94
91 thisdatetime = datetime.datetime.utcfromtimestamp(txmin)
95 thisdatetime = datetime.datetime.utcfromtimestamp(txmin)
92 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
96 thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
93
97
94 if timerange != None:
98 if timerange != None:
95 xmin = (thisdatetime - thisdate).seconds/(60*60.)
99 xmin = (thisdatetime - thisdate).seconds/(60*60.)
96 xmax = xmin + timerange/(60*60.)
100 xmax = xmin + timerange/(60*60.)
97
101
98 mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone)
102 mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone)
99 xmin_sec = time.mktime(mindt.timetuple())
103 xmin_sec = time.mktime(mindt.timetuple())
100
104
101 maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone)
105 maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone)
102 xmax_sec = time.mktime(maxdt.timetuple())
106 xmax_sec = time.mktime(maxdt.timetuple())
103
107
104 return xmin_sec, xmax_sec
108 return xmin_sec, xmax_sec
105
109
106
110
107
111
108
112
109
113
110 # if timerange != None:
114 # if timerange != None:
111 # txmin = x[0] - x[0]%timerange
115 # txmin = x[0] - x[0]%timerange
112 # else:
116 # else:
113 # txmin = numpy.min(x)
117 # txmin = numpy.min(x)
114 #
118 #
115 # thisdatetime = datetime.datetime.utcfromtimestamp(txmin)
119 # thisdatetime = datetime.datetime.utcfromtimestamp(txmin)
116 # thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
120 # thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0))
117 #
121 #
118 # ####################################################
122 # ####################################################
119 # #If the x is out of xrange
123 # #If the x is out of xrange
120 # if xmax != None:
124 # if xmax != None:
121 # if xmax < (thisdatetime - thisdate).seconds/(60*60.):
125 # if xmax < (thisdatetime - thisdate).seconds/(60*60.):
122 # xmin = None
126 # xmin = None
123 # xmax = None
127 # xmax = None
124 #
128 #
125 # if xmin == None:
129 # if xmin == None:
126 # td = thisdatetime - thisdate
130 # td = thisdatetime - thisdate
127 # xmin = td.seconds/(60*60.)
131 # xmin = td.seconds/(60*60.)
128 #
132 #
129 # if xmax == None:
133 # if xmax == None:
130 # xmax = xmin + self.timerange/(60*60.)
134 # xmax = xmin + self.timerange/(60*60.)
131 #
135 #
132 # mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone)
136 # mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone)
133 # tmin = time.mktime(mindt.timetuple())
137 # tmin = time.mktime(mindt.timetuple())
134 #
138 #
135 # maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone)
139 # maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone)
136 # tmax = time.mktime(maxdt.timetuple())
140 # tmax = time.mktime(maxdt.timetuple())
137 #
141 #
138 # #self.timerange = tmax - tmin
142 # #self.timerange = tmax - tmin
139 #
143 #
140 # return tmin, tmax
144 # return tmin, tmax
141
145
142 def init(self, id, nplots, wintitle):
146 def init(self, id, nplots, wintitle):
143
147
144 raise ValueError, "This method has been replaced with createFigure"
148 raise ValueError, "This method has been replaced with createFigure"
145
149
146 def createFigure(self, id, wintitle, widthplot=None, heightplot=None, show=True):
150 def createFigure(self, id, wintitle, widthplot=None, heightplot=None, show=True):
147
151
148 """
152 """
149 Crea la figura de acuerdo al driver y parametros seleccionados seleccionados.
153 Crea la figura de acuerdo al driver y parametros seleccionados seleccionados.
150 Las dimensiones de la pantalla es calculada a partir de los atributos self.WIDTH
154 Las dimensiones de la pantalla es calculada a partir de los atributos self.WIDTH
151 y self.HEIGHT y el numero de subplots (nrow, ncol)
155 y self.HEIGHT y el numero de subplots (nrow, ncol)
152
156
153 Input:
157 Input:
154 id : Los parametros necesarios son
158 id : Los parametros necesarios son
155 wintitle :
159 wintitle :
156
160
157 """
161 """
158
162
159 if widthplot == None:
163 if widthplot == None:
160 widthplot = self.WIDTH
164 widthplot = self.WIDTH
161
165
162 if heightplot == None:
166 if heightplot == None:
163 heightplot = self.HEIGHT
167 heightplot = self.HEIGHT
164
168
165 self.id = id
169 self.id = id
166
170
167 self.wintitle = wintitle
171 self.wintitle = wintitle
168
172
169 self.widthscreen, self.heightscreen = self.getScreenDim(widthplot, heightplot)
173 self.widthscreen, self.heightscreen = self.getScreenDim(widthplot, heightplot)
170
174
171 self.fig = self.__driver.createFigure(id=self.id,
175 self.fig = self.__driver.createFigure(id=self.id,
172 wintitle=self.wintitle,
176 wintitle=self.wintitle,
173 width=self.widthscreen,
177 width=self.widthscreen,
174 height=self.heightscreen,
178 height=self.heightscreen,
175 show=show)
179 show=show)
176
180
177 self.axesObjList = []
181 self.axesObjList = []
182 self.counter_imagwr = 0
178
183
179
184
180 def setDriver(self, driver=mpldriver):
185 def setDriver(self, driver=mpldriver):
181
186
182 self.__driver = driver
187 self.__driver = driver
183
188
184 def setTitle(self, title):
189 def setTitle(self, title):
185
190
186 self.__driver.setTitle(self.fig, title)
191 self.__driver.setTitle(self.fig, title)
187
192
188 def setWinTitle(self, title):
193 def setWinTitle(self, title):
189
194
190 self.__driver.setWinTitle(self.fig, title=title)
195 self.__driver.setWinTitle(self.fig, title=title)
191
196
192 def setTextFromAxes(self, text):
197 def setTextFromAxes(self, text):
193
198
194 raise ValueError, "Este metodo ha sido reemplazaado con el metodo setText de la clase Axes"
199 raise ValueError, "Este metodo ha sido reemplazaado con el metodo setText de la clase Axes"
195
200
196 def makeAxes(self, nrow, ncol, xpos, ypos, colspan, rowspan):
201 def makeAxes(self, nrow, ncol, xpos, ypos, colspan, rowspan):
197
202
198 raise ValueError, "Este metodo ha sido reemplazaado con el metodo addAxes"
203 raise ValueError, "Este metodo ha sido reemplazaado con el metodo addAxes"
199
204
200 def addAxes(self, *args):
205 def addAxes(self, *args):
201 """
206 """
202
207
203 Input:
208 Input:
204 *args : Los parametros necesarios son
209 *args : Los parametros necesarios son
205 nrow, ncol, xpos, ypos, colspan, rowspan
210 nrow, ncol, xpos, ypos, colspan, rowspan
206 """
211 """
207
212
208 axesObj = Axes(self.fig, *args)
213 axesObj = Axes(self.fig, *args)
209 self.axesObjList.append(axesObj)
214 self.axesObjList.append(axesObj)
210
215
211 def saveFigure(self, figpath, figfile, *args):
216 def saveFigure(self, figpath, figfile, *args):
212
217
213 filename = os.path.join(figpath, figfile)
218 filename = os.path.join(figpath, figfile)
214
219
215 fullpath = os.path.split(filename)[0]
220 fullpath = os.path.split(filename)[0]
216
221
217 if not os.path.exists(fullpath):
222 if not os.path.exists(fullpath):
218 subpath = os.path.split(fullpath)[0]
223 subpath = os.path.split(fullpath)[0]
219
224
220 if not os.path.exists(subpath):
225 if not os.path.exists(subpath):
221 os.mkdir(subpath)
226 os.mkdir(subpath)
222
227
223 os.mkdir(fullpath)
228 os.mkdir(fullpath)
224
229
225 self.__driver.saveFigure(self.fig, filename, *args)
230 self.__driver.saveFigure(self.fig, filename, *args)
226
231
227
232 def save(self, figpath, figfile=None, save=True, ftp=False, wr_period=1, thisDatetime=None, update_figfile=True):
228
233
234 if not save:
235 return
236
237 if figfile == None:
238
239 if not thisDatetime:
240 raise ValueError, "Saving figure: figfile or thisDatetime should be defined"
241 return
242
243 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
244 figfile = self.getFilename(name = str_datetime)
245
246 if self.figfile == None:
247 self.figfile = figfile
248
249 if update_figfile:
250 self.figfile = figfile
251
252 self.counter_imagwr += 1
253
254 if self.counter_imagwr<wr_period:
255 return
256
257 # store png plot to local folder
258 self.saveFigure(figpath, self.figfile)
259 self.counter_imagwr = 0
260
261 if not ftp:
262 return
263
264 if not thisDatetime:
265 return
266
267 # store png plot to FTP server according to RT-Web format
268 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
269 ftp_filename = os.path.join(figpath, name)
270 self.saveFigure(figpath, ftp_filename)
229
271
230 def getNameToFtp(self, thisDatetime, FTP_WEI, EXP_CODE, SUB_EXP_CODE, PLOT_CODE, PLOT_POS):
272 def getNameToFtp(self, thisDatetime, FTP_WEI, EXP_CODE, SUB_EXP_CODE, PLOT_CODE, PLOT_POS):
231 YEAR_STR = '%4.4d'%thisDatetime.timetuple().tm_year
273 YEAR_STR = '%4.4d'%thisDatetime.timetuple().tm_year
232 DOY_STR = '%3.3d'%thisDatetime.timetuple().tm_yday
274 DOY_STR = '%3.3d'%thisDatetime.timetuple().tm_yday
233 FTP_WEI = '%2.2d'%FTP_WEI
275 FTP_WEI = '%2.2d'%FTP_WEI
234 EXP_CODE = '%3.3d'%EXP_CODE
276 EXP_CODE = '%3.3d'%EXP_CODE
235 SUB_EXP_CODE = '%2.2d'%SUB_EXP_CODE
277 SUB_EXP_CODE = '%2.2d'%SUB_EXP_CODE
236 PLOT_CODE = '%2.2d'%PLOT_CODE
278 PLOT_CODE = '%2.2d'%PLOT_CODE
237 PLOT_POS = '%2.2d'%PLOT_POS
279 PLOT_POS = '%2.2d'%PLOT_POS
238 name = YEAR_STR + DOY_STR + FTP_WEI + EXP_CODE + SUB_EXP_CODE + PLOT_CODE + PLOT_POS
280 name = YEAR_STR + DOY_STR + FTP_WEI + EXP_CODE + SUB_EXP_CODE + PLOT_CODE + PLOT_POS
239 return name
281 return name
240
282
241 def draw(self):
283 def draw(self):
242
284
243 self.__driver.draw(self.fig)
285 self.__driver.draw(self.fig)
244
286
245 def run(self):
287 def run(self):
246
288
247 raise ValueError, "This method is not implemented"
289 raise ValueError, "This method is not implemented"
248
290
249 def close(self):
291 def close(self):
250
292
251 self.__driver.show(True)
293 self.__driver.show(True)
252
294
253 axesList = property(getAxesObjList)
295 axesList = property(getAxesObjList)
254
296
255
297
256 class Axes:
298 class Axes:
257
299
258 __driver = mpldriver
300 __driver = mpldriver
259 fig = None
301 fig = None
260 ax = None
302 ax = None
261 plot = None
303 plot = None
262 __missing = 1E30
304 __missing = 1E30
263 __firsttime = None
305 __firsttime = None
264
306
265 __showprofile = False
307 __showprofile = False
266
308
267 xmin = None
309 xmin = None
268 xmax = None
310 xmax = None
269 ymin = None
311 ymin = None
270 ymax = None
312 ymax = None
271 zmin = None
313 zmin = None
272 zmax = None
314 zmax = None
273
315
274 x_buffer = None
316 x_buffer = None
275 z_buffer = None
317 z_buffer = None
276
318
277 decimationx = None
319 decimationx = None
278 decimationy = None
320 decimationy = None
279
321
280 __MAXNUMX = 300
322 __MAXNUMX = 300
281 __MAXNUMY = 150
323 __MAXNUMY = 150
282
324
283 def __init__(self, *args):
325 def __init__(self, *args):
284
326
285 """
327 """
286
328
287 Input:
329 Input:
288 *args : Los parametros necesarios son
330 *args : Los parametros necesarios son
289 fig, nrow, ncol, xpos, ypos, colspan, rowspan
331 fig, nrow, ncol, xpos, ypos, colspan, rowspan
290 """
332 """
291
333
292 ax = self.__driver.createAxes(*args)
334 ax = self.__driver.createAxes(*args)
293 self.fig = args[0]
335 self.fig = args[0]
294 self.ax = ax
336 self.ax = ax
295 self.plot = None
337 self.plot = None
296
338
297 self.__firsttime = True
339 self.__firsttime = True
298 self.idlineList = []
340 self.idlineList = []
299
341
300 self.x_buffer = numpy.array([])
342 self.x_buffer = numpy.array([])
301 self.z_buffer = numpy.array([])
343 self.z_buffer = numpy.array([])
302
344
303 def setText(self, text):
345 def setText(self, text):
304
346
305 self.__driver.setAxesText(self.ax, text)
347 self.__driver.setAxesText(self.ax, text)
306
348
307 def setXAxisAsTime(self):
349 def setXAxisAsTime(self):
308 pass
350 pass
309
351
310 def pline(self, x, y,
352 def pline(self, x, y,
311 xmin=None, xmax=None,
353 xmin=None, xmax=None,
312 ymin=None, ymax=None,
354 ymin=None, ymax=None,
313 xlabel='', ylabel='',
355 xlabel='', ylabel='',
314 title='',
356 title='',
315 **kwargs):
357 **kwargs):
316
358
317 """
359 """
318
360
319 Input:
361 Input:
320 x :
362 x :
321 y :
363 y :
322 xmin :
364 xmin :
323 xmax :
365 xmax :
324 ymin :
366 ymin :
325 ymax :
367 ymax :
326 xlabel :
368 xlabel :
327 ylabel :
369 ylabel :
328 title :
370 title :
329 **kwargs : Los parametros aceptados son
371 **kwargs : Los parametros aceptados son
330
372
331 ticksize
373 ticksize
332 ytick_visible
374 ytick_visible
333 """
375 """
334
376
335 if self.__firsttime:
377 if self.__firsttime:
336
378
337 if xmin == None: xmin = numpy.nanmin(x)
379 if xmin == None: xmin = numpy.nanmin(x)
338 if xmax == None: xmax = numpy.nanmax(x)
380 if xmax == None: xmax = numpy.nanmax(x)
339 if ymin == None: ymin = numpy.nanmin(y)
381 if ymin == None: ymin = numpy.nanmin(y)
340 if ymax == None: ymax = numpy.nanmax(y)
382 if ymax == None: ymax = numpy.nanmax(y)
341
383
342 self.plot = self.__driver.createPline(self.ax, x, y,
384 self.plot = self.__driver.createPline(self.ax, x, y,
343 xmin, xmax,
385 xmin, xmax,
344 ymin, ymax,
386 ymin, ymax,
345 xlabel=xlabel,
387 xlabel=xlabel,
346 ylabel=ylabel,
388 ylabel=ylabel,
347 title=title,
389 title=title,
348 **kwargs)
390 **kwargs)
349
391
350 self.idlineList.append(0)
392 self.idlineList.append(0)
351 self.__firsttime = False
393 self.__firsttime = False
352 return
394 return
353
395
354 self.__driver.pline(self.plot, x, y, xlabel=xlabel,
396 self.__driver.pline(self.plot, x, y, xlabel=xlabel,
355 ylabel=ylabel,
397 ylabel=ylabel,
356 title=title)
398 title=title)
357
399
358 def addpline(self, x, y, idline, **kwargs):
400 def addpline(self, x, y, idline, **kwargs):
359 lines = self.ax.lines
401 lines = self.ax.lines
360
402
361 if idline in self.idlineList:
403 if idline in self.idlineList:
362 self.__driver.set_linedata(self.ax, x, y, idline)
404 self.__driver.set_linedata(self.ax, x, y, idline)
363
405
364 if idline not in(self.idlineList):
406 if idline not in(self.idlineList):
365 self.__driver.addpline(self.ax, x, y, **kwargs)
407 self.__driver.addpline(self.ax, x, y, **kwargs)
366 self.idlineList.append(idline)
408 self.idlineList.append(idline)
367
409
368 return
410 return
369
411
370 def pmultiline(self, x, y,
412 def pmultiline(self, x, y,
371 xmin=None, xmax=None,
413 xmin=None, xmax=None,
372 ymin=None, ymax=None,
414 ymin=None, ymax=None,
373 xlabel='', ylabel='',
415 xlabel='', ylabel='',
374 title='',
416 title='',
375 **kwargs):
417 **kwargs):
376
418
377 if self.__firsttime:
419 if self.__firsttime:
378
420
379 if xmin == None: xmin = numpy.nanmin(x)
421 if xmin == None: xmin = numpy.nanmin(x)
380 if xmax == None: xmax = numpy.nanmax(x)
422 if xmax == None: xmax = numpy.nanmax(x)
381 if ymin == None: ymin = numpy.nanmin(y)
423 if ymin == None: ymin = numpy.nanmin(y)
382 if ymax == None: ymax = numpy.nanmax(y)
424 if ymax == None: ymax = numpy.nanmax(y)
383
425
384 self.plot = self.__driver.createPmultiline(self.ax, x, y,
426 self.plot = self.__driver.createPmultiline(self.ax, x, y,
385 xmin, xmax,
427 xmin, xmax,
386 ymin, ymax,
428 ymin, ymax,
387 xlabel=xlabel,
429 xlabel=xlabel,
388 ylabel=ylabel,
430 ylabel=ylabel,
389 title=title,
431 title=title,
390 **kwargs)
432 **kwargs)
391 self.__firsttime = False
433 self.__firsttime = False
392 return
434 return
393
435
394 self.__driver.pmultiline(self.plot, x, y, xlabel=xlabel,
436 self.__driver.pmultiline(self.plot, x, y, xlabel=xlabel,
395 ylabel=ylabel,
437 ylabel=ylabel,
396 title=title)
438 title=title)
397
439
398 def pmultilineyaxis(self, x, y,
440 def pmultilineyaxis(self, x, y,
399 xmin=None, xmax=None,
441 xmin=None, xmax=None,
400 ymin=None, ymax=None,
442 ymin=None, ymax=None,
401 xlabel='', ylabel='',
443 xlabel='', ylabel='',
402 title='',
444 title='',
403 **kwargs):
445 **kwargs):
404
446
405 if self.__firsttime:
447 if self.__firsttime:
406
448
407 if xmin == None: xmin = numpy.nanmin(x)
449 if xmin == None: xmin = numpy.nanmin(x)
408 if xmax == None: xmax = numpy.nanmax(x)
450 if xmax == None: xmax = numpy.nanmax(x)
409 if ymin == None: ymin = numpy.nanmin(y)
451 if ymin == None: ymin = numpy.nanmin(y)
410 if ymax == None: ymax = numpy.nanmax(y)
452 if ymax == None: ymax = numpy.nanmax(y)
411
453
412 self.plot = self.__driver.createPmultilineYAxis(self.ax, x, y,
454 self.plot = self.__driver.createPmultilineYAxis(self.ax, x, y,
413 xmin, xmax,
455 xmin, xmax,
414 ymin, ymax,
456 ymin, ymax,
415 xlabel=xlabel,
457 xlabel=xlabel,
416 ylabel=ylabel,
458 ylabel=ylabel,
417 title=title,
459 title=title,
418 **kwargs)
460 **kwargs)
419 if self.xmin == None: self.xmin = xmin
461 if self.xmin == None: self.xmin = xmin
420 if self.xmax == None: self.xmax = xmax
462 if self.xmax == None: self.xmax = xmax
421 if self.ymin == None: self.ymin = ymin
463 if self.ymin == None: self.ymin = ymin
422 if self.ymax == None: self.ymax = ymax
464 if self.ymax == None: self.ymax = ymax
423
465
424 self.__firsttime = False
466 self.__firsttime = False
425 return
467 return
426
468
427 self.__driver.pmultilineyaxis(self.plot, x, y, xlabel=xlabel,
469 self.__driver.pmultilineyaxis(self.plot, x, y, xlabel=xlabel,
428 ylabel=ylabel,
470 ylabel=ylabel,
429 title=title)
471 title=title)
430
472
431 def pcolor(self, x, y, z,
473 def pcolor(self, x, y, z,
432 xmin=None, xmax=None,
474 xmin=None, xmax=None,
433 ymin=None, ymax=None,
475 ymin=None, ymax=None,
434 zmin=None, zmax=None,
476 zmin=None, zmax=None,
435 xlabel='', ylabel='',
477 xlabel='', ylabel='',
436 title='', rti = False, colormap='jet',
478 title='', rti = False, colormap='jet',
437 **kwargs):
479 **kwargs):
438
480
439 """
481 """
440 Input:
482 Input:
441 x :
483 x :
442 y :
484 y :
443 x :
485 x :
444 xmin :
486 xmin :
445 xmax :
487 xmax :
446 ymin :
488 ymin :
447 ymax :
489 ymax :
448 zmin :
490 zmin :
449 zmax :
491 zmax :
450 xlabel :
492 xlabel :
451 ylabel :
493 ylabel :
452 title :
494 title :
453 **kwargs : Los parametros aceptados son
495 **kwargs : Los parametros aceptados son
454 ticksize=9,
496 ticksize=9,
455 cblabel=''
497 cblabel=''
456 rti = True or False
498 rti = True or False
457 """
499 """
458
500
459 if self.__firsttime:
501 if self.__firsttime:
460
502
461 if xmin == None: xmin = numpy.nanmin(x)
503 if xmin == None: xmin = numpy.nanmin(x)
462 if xmax == None: xmax = numpy.nanmax(x)
504 if xmax == None: xmax = numpy.nanmax(x)
463 if ymin == None: ymin = numpy.nanmin(y)
505 if ymin == None: ymin = numpy.nanmin(y)
464 if ymax == None: ymax = numpy.nanmax(y)
506 if ymax == None: ymax = numpy.nanmax(y)
465 if zmin == None: zmin = numpy.nanmin(z)
507 if zmin == None: zmin = numpy.nanmin(z)
466 if zmax == None: zmax = numpy.nanmax(z)
508 if zmax == None: zmax = numpy.nanmax(z)
467
509
468
510
469 self.plot = self.__driver.createPcolor(self.ax, x, y, z,
511 self.plot = self.__driver.createPcolor(self.ax, x, y, z,
470 xmin, xmax,
512 xmin, xmax,
471 ymin, ymax,
513 ymin, ymax,
472 zmin, zmax,
514 zmin, zmax,
473 xlabel=xlabel,
515 xlabel=xlabel,
474 ylabel=ylabel,
516 ylabel=ylabel,
475 title=title,
517 title=title,
476 colormap=colormap,
518 colormap=colormap,
477 **kwargs)
519 **kwargs)
478
520
479 if self.xmin == None: self.xmin = xmin
521 if self.xmin == None: self.xmin = xmin
480 if self.xmax == None: self.xmax = xmax
522 if self.xmax == None: self.xmax = xmax
481 if self.ymin == None: self.ymin = ymin
523 if self.ymin == None: self.ymin = ymin
482 if self.ymax == None: self.ymax = ymax
524 if self.ymax == None: self.ymax = ymax
483 if self.zmin == None: self.zmin = zmin
525 if self.zmin == None: self.zmin = zmin
484 if self.zmax == None: self.zmax = zmax
526 if self.zmax == None: self.zmax = zmax
485
527
486 self.__firsttime = False
528 self.__firsttime = False
487 return
529 return
488
530
489 if rti:
531 if rti:
490 self.__driver.addpcolor(self.ax, x, y, z, self.zmin, self.zmax,
532 self.__driver.addpcolor(self.ax, x, y, z, self.zmin, self.zmax,
491 xlabel=xlabel,
533 xlabel=xlabel,
492 ylabel=ylabel,
534 ylabel=ylabel,
493 title=title,
535 title=title,
494 colormap=colormap)
536 colormap=colormap)
495 return
537 return
496
538
497 self.__driver.pcolor(self.plot, z,
539 self.__driver.pcolor(self.plot, z,
498 xlabel=xlabel,
540 xlabel=xlabel,
499 ylabel=ylabel,
541 ylabel=ylabel,
500 title=title)
542 title=title)
501
543
502 def pcolorbuffer(self, x, y, z,
544 def pcolorbuffer(self, x, y, z,
503 xmin=None, xmax=None,
545 xmin=None, xmax=None,
504 ymin=None, ymax=None,
546 ymin=None, ymax=None,
505 zmin=None, zmax=None,
547 zmin=None, zmax=None,
506 xlabel='', ylabel='',
548 xlabel='', ylabel='',
507 title='', rti = True, colormap='jet',
549 title='', rti = True, colormap='jet',
508 maxNumX = None, maxNumY = None,
550 maxNumX = None, maxNumY = None,
509 **kwargs):
551 **kwargs):
510
552
511 if maxNumX == None:
553 if maxNumX == None:
512 maxNumX = self.__MAXNUMX
554 maxNumX = self.__MAXNUMX
513
555
514 if maxNumY == None:
556 if maxNumY == None:
515 maxNumY = self.__MAXNUMY
557 maxNumY = self.__MAXNUMY
516
558
517 if self.__firsttime:
559 if self.__firsttime:
518 self.z_buffer = z
560 self.z_buffer = z
519 self.x_buffer = numpy.hstack((self.x_buffer, x))
561 self.x_buffer = numpy.hstack((self.x_buffer, x))
520
562
521 if xmin == None: xmin = numpy.nanmin(x)
563 if xmin == None: xmin = numpy.nanmin(x)
522 if xmax == None: xmax = numpy.nanmax(x)
564 if xmax == None: xmax = numpy.nanmax(x)
523 if ymin == None: ymin = numpy.nanmin(y)
565 if ymin == None: ymin = numpy.nanmin(y)
524 if ymax == None: ymax = numpy.nanmax(y)
566 if ymax == None: ymax = numpy.nanmax(y)
525 if zmin == None: zmin = numpy.nanmin(z)
567 if zmin == None: zmin = numpy.nanmin(z)
526 if zmax == None: zmax = numpy.nanmax(z)
568 if zmax == None: zmax = numpy.nanmax(z)
527
569
528
570
529 self.plot = self.__driver.createPcolor(self.ax, self.x_buffer, y, z,
571 self.plot = self.__driver.createPcolor(self.ax, self.x_buffer, y, z,
530 xmin, xmax,
572 xmin, xmax,
531 ymin, ymax,
573 ymin, ymax,
532 zmin, zmax,
574 zmin, zmax,
533 xlabel=xlabel,
575 xlabel=xlabel,
534 ylabel=ylabel,
576 ylabel=ylabel,
535 title=title,
577 title=title,
536 colormap=colormap,
578 colormap=colormap,
537 **kwargs)
579 **kwargs)
538
580
539 if self.xmin == None: self.xmin = xmin
581 if self.xmin == None: self.xmin = xmin
540 if self.xmax == None: self.xmax = xmax
582 if self.xmax == None: self.xmax = xmax
541 if self.ymin == None: self.ymin = ymin
583 if self.ymin == None: self.ymin = ymin
542 if self.ymax == None: self.ymax = ymax
584 if self.ymax == None: self.ymax = ymax
543 if self.zmin == None: self.zmin = zmin
585 if self.zmin == None: self.zmin = zmin
544 if self.zmax == None: self.zmax = zmax
586 if self.zmax == None: self.zmax = zmax
545
587
546 self.__firsttime = False
588 self.__firsttime = False
547 return
589 return
548
590
549 self.x_buffer = numpy.hstack((self.x_buffer, x[-1]))
591 self.x_buffer = numpy.hstack((self.x_buffer, x[-1]))
550 self.z_buffer = numpy.hstack((self.z_buffer, z))
592 self.z_buffer = numpy.hstack((self.z_buffer, z))
551
593
552 if self.decimationx == None:
594 if self.decimationx == None:
553 deltax = float(self.xmax - self.xmin)/maxNumX
595 deltax = float(self.xmax - self.xmin)/maxNumX
554 deltay = float(self.ymax - self.ymin)/maxNumY
596 deltay = float(self.ymax - self.ymin)/maxNumY
555
597
556 resolutionx = self.x_buffer[2]-self.x_buffer[0]
598 resolutionx = self.x_buffer[2]-self.x_buffer[0]
557 resolutiony = y[1]-y[0]
599 resolutiony = y[1]-y[0]
558
600
559 self.decimationx = numpy.ceil(deltax / resolutionx)
601 self.decimationx = numpy.ceil(deltax / resolutionx)
560 self.decimationy = numpy.ceil(deltay / resolutiony)
602 self.decimationy = numpy.ceil(deltay / resolutiony)
561
603
562 z_buffer = self.z_buffer.reshape(-1,len(y))
604 z_buffer = self.z_buffer.reshape(-1,len(y))
563
605
564 x_buffer = self.x_buffer[::self.decimationx]
606 x_buffer = self.x_buffer[::self.decimationx]
565 y_buffer = y[::self.decimationy]
607 y_buffer = y[::self.decimationy]
566 z_buffer = z_buffer[::self.decimationx, ::self.decimationy]
608 z_buffer = z_buffer[::self.decimationx, ::self.decimationy]
567 #===================================================
609 #===================================================
568
610
569 x_buffer, y_buffer, z_buffer = self.__fillGaps(x_buffer, y_buffer, z_buffer)
611 x_buffer, y_buffer, z_buffer = self.__fillGaps(x_buffer, y_buffer, z_buffer)
570
612
571 self.__driver.addpcolorbuffer(self.ax, x_buffer, y_buffer, z_buffer, self.zmin, self.zmax,
613 self.__driver.addpcolorbuffer(self.ax, x_buffer, y_buffer, z_buffer, self.zmin, self.zmax,
572 xlabel=xlabel,
614 xlabel=xlabel,
573 ylabel=ylabel,
615 ylabel=ylabel,
574 title=title,
616 title=title,
575 colormap=colormap)
617 colormap=colormap)
576
618
577 def polar(self, x, y,
619 def polar(self, x, y,
578 title='', xlabel='',ylabel='',**kwargs):
620 title='', xlabel='',ylabel='',**kwargs):
579
621
580 if self.__firsttime:
622 if self.__firsttime:
581 self.plot = self.__driver.createPolar(self.ax, x, y, title = title, xlabel = xlabel, ylabel = ylabel)
623 self.plot = self.__driver.createPolar(self.ax, x, y, title = title, xlabel = xlabel, ylabel = ylabel)
582 self.__firsttime = False
624 self.__firsttime = False
583 self.x_buffer = x
625 self.x_buffer = x
584 self.y_buffer = y
626 self.y_buffer = y
585 return
627 return
586
628
587 self.x_buffer = numpy.hstack((self.x_buffer,x))
629 self.x_buffer = numpy.hstack((self.x_buffer,x))
588 self.y_buffer = numpy.hstack((self.y_buffer,y))
630 self.y_buffer = numpy.hstack((self.y_buffer,y))
589 self.__driver.polar(self.plot, self.x_buffer, self.y_buffer, xlabel=xlabel,
631 self.__driver.polar(self.plot, self.x_buffer, self.y_buffer, xlabel=xlabel,
590 ylabel=ylabel,
632 ylabel=ylabel,
591 title=title)
633 title=title)
592
634
593 def __fillGaps(self, x_buffer, y_buffer, z_buffer):
635 def __fillGaps(self, x_buffer, y_buffer, z_buffer):
594
636
595 deltas = x_buffer[1:] - x_buffer[0:-1]
637 deltas = x_buffer[1:] - x_buffer[0:-1]
596 x_median = numpy.median(deltas)
638 x_median = numpy.median(deltas)
597
639
598 index = numpy.where(deltas >= 2*x_median)
640 index = numpy.where(deltas >= 2*x_median)
599
641
600 if len(index[0]) != 0:
642 if len(index[0]) != 0:
601 z_buffer[index[0],::] = self.__missing
643 z_buffer[index[0],::] = self.__missing
602 z_buffer = numpy.ma.masked_inside(z_buffer,0.99*self.__missing,1.01*self.__missing)
644 z_buffer = numpy.ma.masked_inside(z_buffer,0.99*self.__missing,1.01*self.__missing)
603
645
604 return x_buffer, y_buffer, z_buffer
646 return x_buffer, y_buffer, z_buffer
605
647
606
648
607
649
608 No newline at end of file
650
@@ -1,198 +1,188
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4 import copy
4 import copy
5
5
6 from figure import Figure, isRealtime
6 from figure import Figure, isRealtime
7
7
8 class CorrelationPlot(Figure):
8 class CorrelationPlot(Figure):
9
9
10 isConfig = None
10 isConfig = None
11 __nsubplots = None
11 __nsubplots = None
12
12
13 WIDTHPROF = None
13 WIDTHPROF = None
14 HEIGHTPROF = None
14 HEIGHTPROF = None
15 PREFIX = 'corr'
15 PREFIX = 'corr'
16
16
17 def __init__(self):
17 def __init__(self):
18
18
19 self.isConfig = False
19 self.isConfig = False
20 self.__nsubplots = 1
20 self.__nsubplots = 1
21
21
22 self.WIDTH = 280
22 self.WIDTH = 280
23 self.HEIGHT = 250
23 self.HEIGHT = 250
24 self.WIDTHPROF = 120
24 self.WIDTHPROF = 120
25 self.HEIGHTPROF = 0
25 self.HEIGHTPROF = 0
26 self.counter_imagwr = 0
26 self.counter_imagwr = 0
27
27
28 self.PLOT_CODE = 1
28 self.PLOT_CODE = 1
29 self.FTP_WEI = None
29 self.FTP_WEI = None
30 self.EXP_CODE = None
30 self.EXP_CODE = None
31 self.SUB_EXP_CODE = None
31 self.SUB_EXP_CODE = None
32 self.PLOT_POS = None
32 self.PLOT_POS = None
33
33
34 def getSubplots(self):
34 def getSubplots(self):
35
35
36 ncol = int(numpy.sqrt(self.nplots)+0.9)
36 ncol = int(numpy.sqrt(self.nplots)+0.9)
37 nrow = int(self.nplots*1./ncol + 0.9)
37 nrow = int(self.nplots*1./ncol + 0.9)
38
38
39 return nrow, ncol
39 return nrow, ncol
40
40
41 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
41 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
42
42
43 showprofile = False
43 showprofile = False
44 self.__showprofile = showprofile
44 self.__showprofile = showprofile
45 self.nplots = nplots
45 self.nplots = nplots
46
46
47 ncolspan = 1
47 ncolspan = 1
48 colspan = 1
48 colspan = 1
49 if showprofile:
49 if showprofile:
50 ncolspan = 3
50 ncolspan = 3
51 colspan = 2
51 colspan = 2
52 self.__nsubplots = 2
52 self.__nsubplots = 2
53
53
54 self.createFigure(id = id,
54 self.createFigure(id = id,
55 wintitle = wintitle,
55 wintitle = wintitle,
56 widthplot = self.WIDTH + self.WIDTHPROF,
56 widthplot = self.WIDTH + self.WIDTHPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
58 show=show)
58 show=show)
59
59
60 nrow, ncol = self.getSubplots()
60 nrow, ncol = self.getSubplots()
61
61
62 counter = 0
62 counter = 0
63 for y in range(nrow):
63 for y in range(nrow):
64 for x in range(ncol):
64 for x in range(ncol):
65
65
66 if counter >= self.nplots:
66 if counter >= self.nplots:
67 break
67 break
68
68
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
70
70
71 if showprofile:
71 if showprofile:
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
73
73
74 counter += 1
74 counter += 1
75
75
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
78 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
78 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
79 server=None, folder=None, username=None, password=None,
79 server=None, folder=None, username=None, password=None,
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
81
81
82 """
82 """
83
83
84 Input:
84 Input:
85 dataOut :
85 dataOut :
86 id :
86 id :
87 wintitle :
87 wintitle :
88 channelList :
88 channelList :
89 showProfile :
89 showProfile :
90 xmin : None,
90 xmin : None,
91 xmax : None,
91 xmax : None,
92 ymin : None,
92 ymin : None,
93 ymax : None,
93 ymax : None,
94 zmin : None,
94 zmin : None,
95 zmax : None
95 zmax : None
96 """
96 """
97
97
98 if dataOut.flagNoData:
98 if dataOut.flagNoData:
99 return None
99 return None
100
100
101 if realtime:
101 if realtime:
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
103 print 'Skipping this plot function'
103 print 'Skipping this plot function'
104 return
104 return
105
105
106 if channelList == None:
106 if channelList == None:
107 channelIndexList = dataOut.channelIndexList
107 channelIndexList = dataOut.channelIndexList
108 else:
108 else:
109 channelIndexList = []
109 channelIndexList = []
110 for channel in channelList:
110 for channel in channelList:
111 if channel not in dataOut.channelList:
111 if channel not in dataOut.channelList:
112 raise ValueError, "Channel %d is not in dataOut.channelList"
112 raise ValueError, "Channel %d is not in dataOut.channelList"
113 channelIndexList.append(dataOut.channelList.index(channel))
113 channelIndexList.append(dataOut.channelList.index(channel))
114
114
115 factor = dataOut.normFactor
115 factor = dataOut.normFactor
116 lenfactor = factor.shape[1]
116 lenfactor = factor.shape[1]
117 x = dataOut.getLagTRange(1)
117 x = dataOut.getLagTRange(1)
118 y = dataOut.getHeiRange()
118 y = dataOut.getHeiRange()
119
119
120 z = copy.copy(dataOut.data_corr[:,:,0,:])
120 z = copy.copy(dataOut.data_corr[:,:,0,:])
121 for i in range(dataOut.data_corr.shape[0]):
121 for i in range(dataOut.data_corr.shape[0]):
122 z[i,:,:] = z[i,:,:]/factor[i,:]
122 z[i,:,:] = z[i,:,:]/factor[i,:]
123 zdB = numpy.abs(z)
123 zdB = numpy.abs(z)
124
124
125 avg = numpy.average(z, axis=1)
125 avg = numpy.average(z, axis=1)
126 # avg = numpy.nanmean(z, axis=1)
126 # avg = numpy.nanmean(z, axis=1)
127 # noise = dataOut.noise/factor
127 # noise = dataOut.noise/factor
128
128
129 #thisDatetime = dataOut.datatime
129 #thisDatetime = dataOut.datatime
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
130 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
131 title = wintitle + " Correlation"
131 title = wintitle + " Correlation"
132 xlabel = "Lag T (s)"
132 xlabel = "Lag T (s)"
133 ylabel = "Range (Km)"
133 ylabel = "Range (Km)"
134
134
135 if not self.isConfig:
135 if not self.isConfig:
136
136
137 nplots = dataOut.data_corr.shape[0]
137 nplots = dataOut.data_corr.shape[0]
138
138
139 self.setup(id=id,
139 self.setup(id=id,
140 nplots=nplots,
140 nplots=nplots,
141 wintitle=wintitle,
141 wintitle=wintitle,
142 showprofile=showprofile,
142 showprofile=showprofile,
143 show=show)
143 show=show)
144
144
145 if xmin == None: xmin = numpy.nanmin(x)
145 if xmin == None: xmin = numpy.nanmin(x)
146 if xmax == None: xmax = numpy.nanmax(x)
146 if xmax == None: xmax = numpy.nanmax(x)
147 if ymin == None: ymin = numpy.nanmin(y)
147 if ymin == None: ymin = numpy.nanmin(y)
148 if ymax == None: ymax = numpy.nanmax(y)
148 if ymax == None: ymax = numpy.nanmax(y)
149 if zmin == None: zmin = 0
149 if zmin == None: zmin = 0
150 if zmax == None: zmax = 1
150 if zmax == None: zmax = 1
151
151
152 self.FTP_WEI = ftp_wei
152 self.FTP_WEI = ftp_wei
153 self.EXP_CODE = exp_code
153 self.EXP_CODE = exp_code
154 self.SUB_EXP_CODE = sub_exp_code
154 self.SUB_EXP_CODE = sub_exp_code
155 self.PLOT_POS = plot_pos
155 self.PLOT_POS = plot_pos
156
156
157 self.isConfig = True
157 self.isConfig = True
158
158
159 self.setWinTitle(title)
159 self.setWinTitle(title)
160
160
161 for i in range(self.nplots):
161 for i in range(self.nplots):
162 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
162 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
163 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0]+1,dataOut.pairsList[i][1]+1 , str_datetime)
163 title = "Channel %d and %d: : %s" %(dataOut.pairsList[i][0]+1,dataOut.pairsList[i][1]+1 , str_datetime)
164 axes = self.axesList[i*self.__nsubplots]
164 axes = self.axesList[i*self.__nsubplots]
165 axes.pcolor(x, y, zdB[i,:,:],
165 axes.pcolor(x, y, zdB[i,:,:],
166 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
166 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
167 xlabel=xlabel, ylabel=ylabel, title=title,
167 xlabel=xlabel, ylabel=ylabel, title=title,
168 ticksize=9, cblabel='')
168 ticksize=9, cblabel='')
169
169
170 # if self.__showprofile:
170 # if self.__showprofile:
171 # axes = self.axesList[i*self.__nsubplots +1]
171 # axes = self.axesList[i*self.__nsubplots +1]
172 # axes.pline(avgdB[i], y,
172 # axes.pline(avgdB[i], y,
173 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
173 # xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
174 # xlabel='dB', ylabel='', title='',
174 # xlabel='dB', ylabel='', title='',
175 # ytick_visible=False,
175 # ytick_visible=False,
176 # grid='x')
176 # grid='x')
177 #
177 #
178 # noiseline = numpy.repeat(noisedB[i], len(y))
178 # noiseline = numpy.repeat(noisedB[i], len(y))
179 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
179 # axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
180
180
181 self.draw()
181 self.draw()
182
182
183 if save:
183 self.save(figpath=figpath,
184
184 figfile=figfile,
185 if figfile == None:
185 save=save,
186 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
186 ftp=ftp,
187 figfile = self.getFilename(name = str_datetime)
187 wr_period=wr_period,
188
188 thisDatetime=thisDatetime)
189 self.counter_imagwr += 1
190 if (self.counter_imagwr>=wr_period):
191 # store png plot to local folder
192 self.saveFigure(figpath, figfile)
193 # store png plot to FTP server according to RT-Web format
194 if ftp:
195 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
196 ftp_filename = os.path.join(figpath, name)
197 self.saveFigure(figpath, ftp_filename)
198 self.counter_imagwr = 0
@@ -1,328 +1,312
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from figure import Figure, isRealtime
10 from figure import Figure, isRealtime
11
11
12 class SpectraHeisScope(Figure):
12 class SpectraHeisScope(Figure):
13
13
14
14
15 isConfig = None
15 isConfig = None
16 __nsubplots = None
16 __nsubplots = None
17
17
18 WIDTHPROF = None
18 WIDTHPROF = None
19 HEIGHTPROF = None
19 HEIGHTPROF = None
20 PREFIX = 'spc'
20 PREFIX = 'spc'
21
21
22 def __init__(self):
22 def __init__(self):
23
23
24 self.isConfig = False
24 self.isConfig = False
25 self.__nsubplots = 1
25 self.__nsubplots = 1
26
26
27 self.WIDTH = 230
27 self.WIDTH = 230
28 self.HEIGHT = 250
28 self.HEIGHT = 250
29 self.WIDTHPROF = 120
29 self.WIDTHPROF = 120
30 self.HEIGHTPROF = 0
30 self.HEIGHTPROF = 0
31 self.counter_imagwr = 0
31 self.counter_imagwr = 0
32
32
33 def getSubplots(self):
33 def getSubplots(self):
34
34
35 ncol = int(numpy.sqrt(self.nplots)+0.9)
35 ncol = int(numpy.sqrt(self.nplots)+0.9)
36 nrow = int(self.nplots*1./ncol + 0.9)
36 nrow = int(self.nplots*1./ncol + 0.9)
37
37
38 return nrow, ncol
38 return nrow, ncol
39
39
40 def setup(self, id, nplots, wintitle, show):
40 def setup(self, id, nplots, wintitle, show):
41
41
42 showprofile = False
42 showprofile = False
43 self.__showprofile = showprofile
43 self.__showprofile = showprofile
44 self.nplots = nplots
44 self.nplots = nplots
45
45
46 ncolspan = 1
46 ncolspan = 1
47 colspan = 1
47 colspan = 1
48 if showprofile:
48 if showprofile:
49 ncolspan = 3
49 ncolspan = 3
50 colspan = 2
50 colspan = 2
51 self.__nsubplots = 2
51 self.__nsubplots = 2
52
52
53 self.createFigure(id = id,
53 self.createFigure(id = id,
54 wintitle = wintitle,
54 wintitle = wintitle,
55 widthplot = self.WIDTH + self.WIDTHPROF,
55 widthplot = self.WIDTH + self.WIDTHPROF,
56 heightplot = self.HEIGHT + self.HEIGHTPROF,
56 heightplot = self.HEIGHT + self.HEIGHTPROF,
57 show = show)
57 show = show)
58
58
59 nrow, ncol = self.getSubplots()
59 nrow, ncol = self.getSubplots()
60
60
61 counter = 0
61 counter = 0
62 for y in range(nrow):
62 for y in range(nrow):
63 for x in range(ncol):
63 for x in range(ncol):
64
64
65 if counter >= self.nplots:
65 if counter >= self.nplots:
66 break
66 break
67
67
68 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
68 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
69
69
70 if showprofile:
70 if showprofile:
71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
71 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
72
72
73 counter += 1
73 counter += 1
74
74
75
75
76 def run(self, dataOut, id, wintitle="", channelList=None,
76 def run(self, dataOut, id, wintitle="", channelList=None,
77 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
77 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
78 figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
78 figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
79 server=None, folder=None, username=None, password=None):
79 server=None, folder=None, username=None, password=None):
80
80
81 """
81 """
82
82
83 Input:
83 Input:
84 dataOut :
84 dataOut :
85 id :
85 id :
86 wintitle :
86 wintitle :
87 channelList :
87 channelList :
88 xmin : None,
88 xmin : None,
89 xmax : None,
89 xmax : None,
90 ymin : None,
90 ymin : None,
91 ymax : None,
91 ymax : None,
92 """
92 """
93
93
94 if dataOut.realtime:
94 if dataOut.realtime:
95 if not(isRealtime(utcdatatime = dataOut.utctime)):
95 if not(isRealtime(utcdatatime = dataOut.utctime)):
96 print 'Skipping this plot function'
96 print 'Skipping this plot function'
97 return
97 return
98
98
99 if channelList == None:
99 if channelList == None:
100 channelIndexList = dataOut.channelIndexList
100 channelIndexList = dataOut.channelIndexList
101 else:
101 else:
102 channelIndexList = []
102 channelIndexList = []
103 for channel in channelList:
103 for channel in channelList:
104 if channel not in dataOut.channelList:
104 if channel not in dataOut.channelList:
105 raise ValueError, "Channel %d is not in dataOut.channelList"
105 raise ValueError, "Channel %d is not in dataOut.channelList"
106 channelIndexList.append(dataOut.channelList.index(channel))
106 channelIndexList.append(dataOut.channelList.index(channel))
107
107
108 # x = dataOut.heightList
108 # x = dataOut.heightList
109 c = 3E8
109 c = 3E8
110 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
110 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
111 #deberia cambiar para el caso de 1Mhz y 100KHz
111 #deberia cambiar para el caso de 1Mhz y 100KHz
112 x = numpy.arange(-1*dataOut.nHeights/2.,dataOut.nHeights/2.)*(c/(2*deltaHeight*dataOut.nHeights*1000))
112 x = numpy.arange(-1*dataOut.nHeights/2.,dataOut.nHeights/2.)*(c/(2*deltaHeight*dataOut.nHeights*1000))
113 #para 1Mhz descomentar la siguiente linea
113 #para 1Mhz descomentar la siguiente linea
114 #x= x/(10000.0)
114 #x= x/(10000.0)
115 # y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
115 # y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
116 # y = y.real
116 # y = y.real
117 factor = dataOut.normFactor
117 factor = dataOut.normFactor
118 data = dataOut.data_spc / factor
118 data = dataOut.data_spc / factor
119 datadB = 10.*numpy.log10(data)
119 datadB = 10.*numpy.log10(data)
120 y = datadB
120 y = datadB
121
121
122 #thisDatetime = dataOut.datatime
122 #thisDatetime = dataOut.datatime
123 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
123 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
124 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
124 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
125 xlabel = ""
125 xlabel = ""
126 #para 1Mhz descomentar la siguiente linea
126 #para 1Mhz descomentar la siguiente linea
127 #xlabel = "Frequency x 10000"
127 #xlabel = "Frequency x 10000"
128 ylabel = "Intensity (dB)"
128 ylabel = "Intensity (dB)"
129
129
130 if not self.isConfig:
130 if not self.isConfig:
131 nplots = len(channelIndexList)
131 nplots = len(channelIndexList)
132
132
133 self.setup(id=id,
133 self.setup(id=id,
134 nplots=nplots,
134 nplots=nplots,
135 wintitle=wintitle,
135 wintitle=wintitle,
136 show=show)
136 show=show)
137
137
138 if xmin == None: xmin = numpy.nanmin(x)
138 if xmin == None: xmin = numpy.nanmin(x)
139 if xmax == None: xmax = numpy.nanmax(x)
139 if xmax == None: xmax = numpy.nanmax(x)
140 if ymin == None: ymin = numpy.nanmin(y)
140 if ymin == None: ymin = numpy.nanmin(y)
141 if ymax == None: ymax = numpy.nanmax(y)
141 if ymax == None: ymax = numpy.nanmax(y)
142
142
143 self.isConfig = True
143 self.isConfig = True
144
144
145 self.setWinTitle(title)
145 self.setWinTitle(title)
146
146
147 for i in range(len(self.axesList)):
147 for i in range(len(self.axesList)):
148 ychannel = y[i,:]
148 ychannel = y[i,:]
149 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
149 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
150 title = "Channel %d: %4.2fdB: %s" %(i, numpy.max(ychannel), str_datetime)
150 title = "Channel %d: %4.2fdB: %s" %(i, numpy.max(ychannel), str_datetime)
151 axes = self.axesList[i]
151 axes = self.axesList[i]
152 axes.pline(x, ychannel,
152 axes.pline(x, ychannel,
153 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
153 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
154 xlabel=xlabel, ylabel=ylabel, title=title, grid='both')
154 xlabel=xlabel, ylabel=ylabel, title=title, grid='both')
155
155
156
156
157 self.draw()
157 self.draw()
158
158
159 if save:
159 self.save(figpath=figpath,
160
160 figfile=figfile,
161 if figfile == None:
161 save=save,
162 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
162 ftp=ftp,
163 figfile = self.getFilename(name = str_datetime)
163 wr_period=wr_period,
164
164 thisDatetime=thisDatetime)
165 self.counter_imagwr += 1
166 if (self.counter_imagwr>=wr_period):
167 # store png plot to local folder
168 self.saveFigure(figpath, figfile)
169 # store png plot to FTP server according to RT-Web format
170 #name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
171 #ftp_filename = os.path.join(figpath, name)
172 #self.saveFigure(figpath, ftp_filename)
173 self.counter_imagwr = 0
174
165
175 class RTIfromSpectraHeis(Figure):
166 class RTIfromSpectraHeis(Figure):
176
167
177 isConfig = None
168 isConfig = None
178 __nsubplots = None
169 __nsubplots = None
179
170
180 PREFIX = 'rtinoise'
171 PREFIX = 'rtinoise'
181
172
182 def __init__(self):
173 def __init__(self):
183
174
184 self.timerange = 24*60*60
175 self.timerange = 24*60*60
185 self.isConfig = False
176 self.isConfig = False
186 self.__nsubplots = 1
177 self.__nsubplots = 1
187
178
188 self.WIDTH = 820
179 self.WIDTH = 820
189 self.HEIGHT = 200
180 self.HEIGHT = 200
190 self.WIDTHPROF = 120
181 self.WIDTHPROF = 120
191 self.HEIGHTPROF = 0
182 self.HEIGHTPROF = 0
192 self.counter_imagwr = 0
183 self.counter_imagwr = 0
193 self.xdata = None
184 self.xdata = None
194 self.ydata = None
185 self.ydata = None
195 self.figfile = None
186 self.figfile = None
196
187
197 def getSubplots(self):
188 def getSubplots(self):
198
189
199 ncol = 1
190 ncol = 1
200 nrow = 1
191 nrow = 1
201
192
202 return nrow, ncol
193 return nrow, ncol
203
194
204 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
195 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
205
196
206 self.__showprofile = showprofile
197 self.__showprofile = showprofile
207 self.nplots = nplots
198 self.nplots = nplots
208
199
209 ncolspan = 7
200 ncolspan = 7
210 colspan = 6
201 colspan = 6
211 self.__nsubplots = 2
202 self.__nsubplots = 2
212
203
213 self.createFigure(id = id,
204 self.createFigure(id = id,
214 wintitle = wintitle,
205 wintitle = wintitle,
215 widthplot = self.WIDTH+self.WIDTHPROF,
206 widthplot = self.WIDTH+self.WIDTHPROF,
216 heightplot = self.HEIGHT+self.HEIGHTPROF,
207 heightplot = self.HEIGHT+self.HEIGHTPROF,
217 show = show)
208 show = show)
218
209
219 nrow, ncol = self.getSubplots()
210 nrow, ncol = self.getSubplots()
220
211
221 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
212 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
222
213
223
214
224 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
215 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
225 xmin=None, xmax=None, ymin=None, ymax=None,
216 xmin=None, xmax=None, ymin=None, ymax=None,
226 timerange=None,
217 timerange=None,
227 save=False, figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
218 save=False, figpath='./', figfile=None, ftp=False, wr_period=1, show=True,
228 server=None, folder=None, username=None, password=None):
219 server=None, folder=None, username=None, password=None):
229
220
230 if channelList == None:
221 if channelList == None:
231 channelIndexList = dataOut.channelIndexList
222 channelIndexList = dataOut.channelIndexList
232 channelList = dataOut.channelList
223 channelList = dataOut.channelList
233 else:
224 else:
234 channelIndexList = []
225 channelIndexList = []
235 for channel in channelList:
226 for channel in channelList:
236 if channel not in dataOut.channelList:
227 if channel not in dataOut.channelList:
237 raise ValueError, "Channel %d is not in dataOut.channelList"
228 raise ValueError, "Channel %d is not in dataOut.channelList"
238 channelIndexList.append(dataOut.channelList.index(channel))
229 channelIndexList.append(dataOut.channelList.index(channel))
239
230
240 if timerange != None:
231 if timerange != None:
241 self.timerange = timerange
232 self.timerange = timerange
242
233
243 tmin = None
234 tmin = None
244 tmax = None
235 tmax = None
245 x = dataOut.getTimeRange()
236 x = dataOut.getTimeRange()
246 y = dataOut.getHeiRange()
237 y = dataOut.getHeiRange()
247
238
248 factor = dataOut.normFactor
239 factor = dataOut.normFactor
249 data = dataOut.data_spc / factor
240 data = dataOut.data_spc / factor
250 data = numpy.average(data,axis=1)
241 data = numpy.average(data,axis=1)
251 datadB = 10*numpy.log10(data)
242 datadB = 10*numpy.log10(data)
252
243
253 # factor = dataOut.normFactor
244 # factor = dataOut.normFactor
254 # noise = dataOut.getNoise()/factor
245 # noise = dataOut.getNoise()/factor
255 # noisedB = 10*numpy.log10(noise)
246 # noisedB = 10*numpy.log10(noise)
256
247
257 #thisDatetime = dataOut.datatime
248 #thisDatetime = dataOut.datatime
258 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
249 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
259 title = wintitle + " RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
250 title = wintitle + " RTI: %s" %(thisDatetime.strftime("%d-%b-%Y"))
260 xlabel = "Local Time"
251 xlabel = "Local Time"
261 ylabel = "Intensity (dB)"
252 ylabel = "Intensity (dB)"
262
253
263 if not self.isConfig:
254 if not self.isConfig:
264
255
265 nplots = 1
256 nplots = 1
266
257
267 self.setup(id=id,
258 self.setup(id=id,
268 nplots=nplots,
259 nplots=nplots,
269 wintitle=wintitle,
260 wintitle=wintitle,
270 showprofile=showprofile,
261 showprofile=showprofile,
271 show=show)
262 show=show)
272
263
273 tmin, tmax = self.getTimeLim(x, xmin, xmax)
264 tmin, tmax = self.getTimeLim(x, xmin, xmax)
274 if ymin == None: ymin = numpy.nanmin(datadB)
265 if ymin == None: ymin = numpy.nanmin(datadB)
275 if ymax == None: ymax = numpy.nanmax(datadB)
266 if ymax == None: ymax = numpy.nanmax(datadB)
276
267
277 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
268 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
278 self.isConfig = True
269 self.isConfig = True
279 self.figfile = figfile
270 self.figfile = figfile
280 self.xdata = numpy.array([])
271 self.xdata = numpy.array([])
281 self.ydata = numpy.array([])
272 self.ydata = numpy.array([])
282
273
283 self.setWinTitle(title)
274 self.setWinTitle(title)
284
275
285
276
286 # title = "RTI %s" %(thisDatetime.strftime("%d-%b-%Y"))
277 # title = "RTI %s" %(thisDatetime.strftime("%d-%b-%Y"))
287 title = "RTI - %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
278 title = "RTI - %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
288
279
289 legendlabels = ["channel %d"%idchannel for idchannel in channelList]
280 legendlabels = ["channel %d"%idchannel for idchannel in channelList]
290 axes = self.axesList[0]
281 axes = self.axesList[0]
291
282
292 self.xdata = numpy.hstack((self.xdata, x[0:1]))
283 self.xdata = numpy.hstack((self.xdata, x[0:1]))
293
284
294 if len(self.ydata)==0:
285 if len(self.ydata)==0:
295 self.ydata = datadB[channelIndexList].reshape(-1,1)
286 self.ydata = datadB[channelIndexList].reshape(-1,1)
296 else:
287 else:
297 self.ydata = numpy.hstack((self.ydata, datadB[channelIndexList].reshape(-1,1)))
288 self.ydata = numpy.hstack((self.ydata, datadB[channelIndexList].reshape(-1,1)))
298
289
299
290
300 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
291 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
301 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax,
292 xmin=tmin, xmax=tmax, ymin=ymin, ymax=ymax,
302 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='.', markersize=8, linestyle="solid", grid='both',
293 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='.', markersize=8, linestyle="solid", grid='both',
303 XAxisAsTime=True
294 XAxisAsTime=True
304 )
295 )
305
296
306 self.draw()
297 self.draw()
307
298
308 if x[1] >= self.axesList[0].xmax:
299 if x[1] >= self.axesList[0].xmax:
309 self.counter_imagwr = wr_period
300 self.counter_imagwr = wr_period
310 del self.xdata
301 del self.xdata
311 del self.ydata
302 del self.ydata
312 self.__isConfig = False
303 self.__isConfig = False
313
304 self.figfile = None
314 if save:
315
305
316 if self.figfile == None:
306 self.save(figpath=figpath,
317 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
307 figfile=figfile,
318 self.figfile = self.getFilename(name = str_datetime)
308 save=save,
319
309 ftp=ftp,
320 self.counter_imagwr += 1
310 wr_period=wr_period,
321 if (self.counter_imagwr>=wr_period):
311 thisDatetime=thisDatetime,
322 # store png plot to local folder
312 update_figfile=False)
323 self.saveFigure(figpath, self.figfile)
324 # store png plot to FTP server according to RT-Web format
325 #name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
326 #ftp_filename = os.path.join(figpath, name)
327 #self.saveFigure(figpath, ftp_filename)
328 self.counter_imagwr = 0
@@ -1,1208 +1,1148
1 import os
1 import os
2 import datetime
2 import datetime
3 import numpy
3 import numpy
4
4
5 from figure import Figure, isRealtime
5 from figure import Figure, isRealtime
6 from plotting_codes import *
6
7
7 class MomentsPlot(Figure):
8 class MomentsPlot(Figure):
8
9
9 isConfig = None
10 isConfig = None
10 __nsubplots = None
11 __nsubplots = None
11
12
12 WIDTHPROF = None
13 WIDTHPROF = None
13 HEIGHTPROF = None
14 HEIGHTPROF = None
14 PREFIX = 'prm'
15 PREFIX = 'prm'
15
16
16 def __init__(self):
17 def __init__(self):
17
18
18 self.isConfig = False
19 self.isConfig = False
19 self.__nsubplots = 1
20 self.__nsubplots = 1
20
21
21 self.WIDTH = 280
22 self.WIDTH = 280
22 self.HEIGHT = 250
23 self.HEIGHT = 250
23 self.WIDTHPROF = 120
24 self.WIDTHPROF = 120
24 self.HEIGHTPROF = 0
25 self.HEIGHTPROF = 0
25 self.counter_imagwr = 0
26 self.counter_imagwr = 0
26
27
27 self.PLOT_CODE = 1
28 self.PLOT_CODE = MOMENTS_CODE
29
28 self.FTP_WEI = None
30 self.FTP_WEI = None
29 self.EXP_CODE = None
31 self.EXP_CODE = None
30 self.SUB_EXP_CODE = None
32 self.SUB_EXP_CODE = None
31 self.PLOT_POS = None
33 self.PLOT_POS = None
32
34
33 def getSubplots(self):
35 def getSubplots(self):
34
36
35 ncol = int(numpy.sqrt(self.nplots)+0.9)
37 ncol = int(numpy.sqrt(self.nplots)+0.9)
36 nrow = int(self.nplots*1./ncol + 0.9)
38 nrow = int(self.nplots*1./ncol + 0.9)
37
39
38 return nrow, ncol
40 return nrow, ncol
39
41
40 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
42 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
41
43
42 self.__showprofile = showprofile
44 self.__showprofile = showprofile
43 self.nplots = nplots
45 self.nplots = nplots
44
46
45 ncolspan = 1
47 ncolspan = 1
46 colspan = 1
48 colspan = 1
47 if showprofile:
49 if showprofile:
48 ncolspan = 3
50 ncolspan = 3
49 colspan = 2
51 colspan = 2
50 self.__nsubplots = 2
52 self.__nsubplots = 2
51
53
52 self.createFigure(id = id,
54 self.createFigure(id = id,
53 wintitle = wintitle,
55 wintitle = wintitle,
54 widthplot = self.WIDTH + self.WIDTHPROF,
56 widthplot = self.WIDTH + self.WIDTHPROF,
55 heightplot = self.HEIGHT + self.HEIGHTPROF,
57 heightplot = self.HEIGHT + self.HEIGHTPROF,
56 show=show)
58 show=show)
57
59
58 nrow, ncol = self.getSubplots()
60 nrow, ncol = self.getSubplots()
59
61
60 counter = 0
62 counter = 0
61 for y in range(nrow):
63 for y in range(nrow):
62 for x in range(ncol):
64 for x in range(ncol):
63
65
64 if counter >= self.nplots:
66 if counter >= self.nplots:
65 break
67 break
66
68
67 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
69 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
68
70
69 if showprofile:
71 if showprofile:
70 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
72 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
71
73
72 counter += 1
74 counter += 1
73
75
74 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
76 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
75 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
77 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
76 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
78 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
77 server=None, folder=None, username=None, password=None,
79 server=None, folder=None, username=None, password=None,
78 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
80 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
79
81
80 """
82 """
81
83
82 Input:
84 Input:
83 dataOut :
85 dataOut :
84 id :
86 id :
85 wintitle :
87 wintitle :
86 channelList :
88 channelList :
87 showProfile :
89 showProfile :
88 xmin : None,
90 xmin : None,
89 xmax : None,
91 xmax : None,
90 ymin : None,
92 ymin : None,
91 ymax : None,
93 ymax : None,
92 zmin : None,
94 zmin : None,
93 zmax : None
95 zmax : None
94 """
96 """
95
97
96 if dataOut.flagNoData:
98 if dataOut.flagNoData:
97 return None
99 return None
98
100
99 if realtime:
101 if realtime:
100 if not(isRealtime(utcdatatime = dataOut.utctime)):
102 if not(isRealtime(utcdatatime = dataOut.utctime)):
101 print 'Skipping this plot function'
103 print 'Skipping this plot function'
102 return
104 return
103
105
104 if channelList == None:
106 if channelList == None:
105 channelIndexList = dataOut.channelIndexList
107 channelIndexList = dataOut.channelIndexList
106 else:
108 else:
107 channelIndexList = []
109 channelIndexList = []
108 for channel in channelList:
110 for channel in channelList:
109 if channel not in dataOut.channelList:
111 if channel not in dataOut.channelList:
110 raise ValueError, "Channel %d is not in dataOut.channelList"
112 raise ValueError, "Channel %d is not in dataOut.channelList"
111 channelIndexList.append(dataOut.channelList.index(channel))
113 channelIndexList.append(dataOut.channelList.index(channel))
112
114
113 factor = dataOut.normFactor
115 factor = dataOut.normFactor
114 x = dataOut.abscissaList
116 x = dataOut.abscissaList
115 y = dataOut.heightList
117 y = dataOut.heightList
116
118
117 z = dataOut.data_pre[channelIndexList,:,:]/factor
119 z = dataOut.data_pre[channelIndexList,:,:]/factor
118 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
120 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
119 avg = numpy.average(z, axis=1)
121 avg = numpy.average(z, axis=1)
120 noise = dataOut.noise/factor
122 noise = dataOut.noise/factor
121
123
122 zdB = 10*numpy.log10(z)
124 zdB = 10*numpy.log10(z)
123 avgdB = 10*numpy.log10(avg)
125 avgdB = 10*numpy.log10(avg)
124 noisedB = 10*numpy.log10(noise)
126 noisedB = 10*numpy.log10(noise)
125
127
126 #thisDatetime = dataOut.datatime
128 #thisDatetime = dataOut.datatime
127 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
129 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
128 title = wintitle + " Parameters"
130 title = wintitle + " Parameters"
129 xlabel = "Velocity (m/s)"
131 xlabel = "Velocity (m/s)"
130 ylabel = "Range (Km)"
132 ylabel = "Range (Km)"
131
133
132 if not self.isConfig:
134 if not self.isConfig:
133
135
134 nplots = len(channelIndexList)
136 nplots = len(channelIndexList)
135
137
136 self.setup(id=id,
138 self.setup(id=id,
137 nplots=nplots,
139 nplots=nplots,
138 wintitle=wintitle,
140 wintitle=wintitle,
139 showprofile=showprofile,
141 showprofile=showprofile,
140 show=show)
142 show=show)
141
143
142 if xmin == None: xmin = numpy.nanmin(x)
144 if xmin == None: xmin = numpy.nanmin(x)
143 if xmax == None: xmax = numpy.nanmax(x)
145 if xmax == None: xmax = numpy.nanmax(x)
144 if ymin == None: ymin = numpy.nanmin(y)
146 if ymin == None: ymin = numpy.nanmin(y)
145 if ymax == None: ymax = numpy.nanmax(y)
147 if ymax == None: ymax = numpy.nanmax(y)
146 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
148 if zmin == None: zmin = numpy.nanmin(avgdB)*0.9
147 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
149 if zmax == None: zmax = numpy.nanmax(avgdB)*0.9
148
150
149 self.FTP_WEI = ftp_wei
151 self.FTP_WEI = ftp_wei
150 self.EXP_CODE = exp_code
152 self.EXP_CODE = exp_code
151 self.SUB_EXP_CODE = sub_exp_code
153 self.SUB_EXP_CODE = sub_exp_code
152 self.PLOT_POS = plot_pos
154 self.PLOT_POS = plot_pos
153
155
154 self.isConfig = True
156 self.isConfig = True
155
157
156 self.setWinTitle(title)
158 self.setWinTitle(title)
157
159
158 for i in range(self.nplots):
160 for i in range(self.nplots):
159 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
161 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
160 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i]+1, noisedB[i], str_datetime)
162 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i]+1, noisedB[i], str_datetime)
161 axes = self.axesList[i*self.__nsubplots]
163 axes = self.axesList[i*self.__nsubplots]
162 axes.pcolor(x, y, zdB[i,:,:],
164 axes.pcolor(x, y, zdB[i,:,:],
163 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
165 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
164 xlabel=xlabel, ylabel=ylabel, title=title,
166 xlabel=xlabel, ylabel=ylabel, title=title,
165 ticksize=9, cblabel='')
167 ticksize=9, cblabel='')
166 #Mean Line
168 #Mean Line
167 mean = dataOut.data_param[i, 1, :]
169 mean = dataOut.data_param[i, 1, :]
168 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
170 axes.addpline(mean, y, idline=0, color="black", linestyle="solid", lw=1)
169
171
170 if self.__showprofile:
172 if self.__showprofile:
171 axes = self.axesList[i*self.__nsubplots +1]
173 axes = self.axesList[i*self.__nsubplots +1]
172 axes.pline(avgdB[i], y,
174 axes.pline(avgdB[i], y,
173 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
175 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
174 xlabel='dB', ylabel='', title='',
176 xlabel='dB', ylabel='', title='',
175 ytick_visible=False,
177 ytick_visible=False,
176 grid='x')
178 grid='x')
177
179
178 noiseline = numpy.repeat(noisedB[i], len(y))
180 noiseline = numpy.repeat(noisedB[i], len(y))
179 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
181 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
180
182
181 self.draw()
183 self.draw()
182
183 if save:
184
185 if figfile == None:
186 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
187 figfile = self.getFilename(name = str_datetime)
188
184
189 self.counter_imagwr += 1
185 self.save(figpath=figpath,
190 if (self.counter_imagwr>=wr_period):
186 figfile=figfile,
191 # store png plot to local folder
187 save=save,
192 self.saveFigure(figpath, figfile)
188 ftp=ftp,
193 self.counter_imagwr = 0
189 wr_period=wr_period,
194 # store png plot to FTP server according to RT-Web format
190 thisDatetime=thisDatetime)
195 if ftp:
196 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
197 ftp_filename = os.path.join(figpath, name)
198 self.saveFigure(figpath, ftp_filename)
199
191
200
192
201
193
202 class SkyMapPlot(Figure):
194 class SkyMapPlot(Figure):
203
195
204 __isConfig = None
196 __isConfig = None
205 __nsubplots = None
197 __nsubplots = None
206
198
207 WIDTHPROF = None
199 WIDTHPROF = None
208 HEIGHTPROF = None
200 HEIGHTPROF = None
209 PREFIX = 'prm'
201 PREFIX = 'prm'
210
202
211 def __init__(self):
203 def __init__(self):
212
204
213 self.__isConfig = False
205 self.__isConfig = False
214 self.__nsubplots = 1
206 self.__nsubplots = 1
215
207
216 # self.WIDTH = 280
208 # self.WIDTH = 280
217 # self.HEIGHT = 250
209 # self.HEIGHT = 250
218 self.WIDTH = 600
210 self.WIDTH = 600
219 self.HEIGHT = 600
211 self.HEIGHT = 600
220 self.WIDTHPROF = 120
212 self.WIDTHPROF = 120
221 self.HEIGHTPROF = 0
213 self.HEIGHTPROF = 0
222 self.counter_imagwr = 0
214 self.counter_imagwr = 0
223
215
224 self.PLOT_CODE = 1
216 self.PLOT_CODE = SKYMAP_CODE
217
225 self.FTP_WEI = None
218 self.FTP_WEI = None
226 self.EXP_CODE = None
219 self.EXP_CODE = None
227 self.SUB_EXP_CODE = None
220 self.SUB_EXP_CODE = None
228 self.PLOT_POS = None
221 self.PLOT_POS = None
229
222
230 def getSubplots(self):
223 def getSubplots(self):
231
224
232 ncol = int(numpy.sqrt(self.nplots)+0.9)
225 ncol = int(numpy.sqrt(self.nplots)+0.9)
233 nrow = int(self.nplots*1./ncol + 0.9)
226 nrow = int(self.nplots*1./ncol + 0.9)
234
227
235 return nrow, ncol
228 return nrow, ncol
236
229
237 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
230 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
238
231
239 self.__showprofile = showprofile
232 self.__showprofile = showprofile
240 self.nplots = nplots
233 self.nplots = nplots
241
234
242 ncolspan = 1
235 ncolspan = 1
243 colspan = 1
236 colspan = 1
244
237
245 self.createFigure(id = id,
238 self.createFigure(id = id,
246 wintitle = wintitle,
239 wintitle = wintitle,
247 widthplot = self.WIDTH, #+ self.WIDTHPROF,
240 widthplot = self.WIDTH, #+ self.WIDTHPROF,
248 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
241 heightplot = self.HEIGHT,# + self.HEIGHTPROF,
249 show=show)
242 show=show)
250
243
251 nrow, ncol = 1,1
244 nrow, ncol = 1,1
252 counter = 0
245 counter = 0
253 x = 0
246 x = 0
254 y = 0
247 y = 0
255 self.addAxes(1, 1, 0, 0, 1, 1, True)
248 self.addAxes(1, 1, 0, 0, 1, 1, True)
256
249
257 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
250 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
258 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
251 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
259 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
252 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
260 server=None, folder=None, username=None, password=None,
253 server=None, folder=None, username=None, password=None,
261 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
254 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
262
255
263 """
256 """
264
257
265 Input:
258 Input:
266 dataOut :
259 dataOut :
267 id :
260 id :
268 wintitle :
261 wintitle :
269 channelList :
262 channelList :
270 showProfile :
263 showProfile :
271 xmin : None,
264 xmin : None,
272 xmax : None,
265 xmax : None,
273 ymin : None,
266 ymin : None,
274 ymax : None,
267 ymax : None,
275 zmin : None,
268 zmin : None,
276 zmax : None
269 zmax : None
277 """
270 """
278
271
279 arrayParameters = dataOut.data_param
272 arrayParameters = dataOut.data_param
280 error = arrayParameters[:,-1]
273 error = arrayParameters[:,-1]
281 indValid = numpy.where(error == 0)[0]
274 indValid = numpy.where(error == 0)[0]
282 finalMeteor = arrayParameters[indValid,:]
275 finalMeteor = arrayParameters[indValid,:]
283 finalAzimuth = finalMeteor[:,4]
276 finalAzimuth = finalMeteor[:,4]
284 finalZenith = finalMeteor[:,5]
277 finalZenith = finalMeteor[:,5]
285
278
286 x = finalAzimuth*numpy.pi/180
279 x = finalAzimuth*numpy.pi/180
287 y = finalZenith
280 y = finalZenith
288
281
289
282
290 #thisDatetime = dataOut.datatime
283 #thisDatetime = dataOut.datatime
291 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
284 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
292 title = wintitle + " Parameters"
285 title = wintitle + " Parameters"
293 xlabel = "Zonal Zenith Angle (deg) "
286 xlabel = "Zonal Zenith Angle (deg) "
294 ylabel = "Meridional Zenith Angle (deg)"
287 ylabel = "Meridional Zenith Angle (deg)"
295
288
296 if not self.__isConfig:
289 if not self.__isConfig:
297
290
298 nplots = 1
291 nplots = 1
299
292
300 self.setup(id=id,
293 self.setup(id=id,
301 nplots=nplots,
294 nplots=nplots,
302 wintitle=wintitle,
295 wintitle=wintitle,
303 showprofile=showprofile,
296 showprofile=showprofile,
304 show=show)
297 show=show)
305
298
306 self.FTP_WEI = ftp_wei
299 self.FTP_WEI = ftp_wei
307 self.EXP_CODE = exp_code
300 self.EXP_CODE = exp_code
308 self.SUB_EXP_CODE = sub_exp_code
301 self.SUB_EXP_CODE = sub_exp_code
309 self.PLOT_POS = plot_pos
302 self.PLOT_POS = plot_pos
310 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
303 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
311 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
304 self.firstdate = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
312 self.__isConfig = True
305 self.__isConfig = True
313
306
314 self.setWinTitle(title)
307 self.setWinTitle(title)
315
308
316 i = 0
309 i = 0
317 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
310 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
318
311
319 axes = self.axesList[i*self.__nsubplots]
312 axes = self.axesList[i*self.__nsubplots]
320 nevents = axes.x_buffer.shape[0] + x.shape[0]
313 nevents = axes.x_buffer.shape[0] + x.shape[0]
321 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
314 title = "Meteor Detection Sky Map\n %s - %s \n Number of events: %5.0f\n" %(self.firstdate,str_datetime,nevents)
322 axes.polar(x, y,
315 axes.polar(x, y,
323 title=title, xlabel=xlabel, ylabel=ylabel,
316 title=title, xlabel=xlabel, ylabel=ylabel,
324 ticksize=9, cblabel='')
317 ticksize=9, cblabel='')
325
318
326 self.draw()
319 self.draw()
327
328 if save:
329
320
330 self.counter_imagwr += 1
321 self.save(figpath=figpath,
331 if (self.counter_imagwr==wr_period):
322 figfile=figfile,
332
323 save=save,
333 if figfile == None:
324 ftp=ftp,
334 figfile = self.getFilename(name = self.name)
325 wr_period=wr_period,
335
326 thisDatetime=thisDatetime)
336 self.saveFigure(figpath, figfile)
337 self.counter_imagwr = 0
338
339 if ftp:
340 #provisionalmente envia archivos en el formato de la web en tiempo real
341 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
342 path = '%s%03d' %(self.PREFIX, self.id)
343 ftp_file = os.path.join(path,'ftp','%s.png'%name)
344 self.saveFigure(figpath, ftp_file)
345 ftp_filename = os.path.join(figpath,ftp_file)
346
347
348 try:
349 self.sendByFTP(ftp_filename, server, folder, username, password)
350 except:
351 self.counter_imagwr = 0
352 raise ValueError, 'Error FTP'
353
354
355
356
327
357 class WindProfilerPlot(Figure):
328 class WindProfilerPlot(Figure):
358
329
359 __isConfig = None
330 __isConfig = None
360 __nsubplots = None
331 __nsubplots = None
361
332
362 WIDTHPROF = None
333 WIDTHPROF = None
363 HEIGHTPROF = None
334 HEIGHTPROF = None
364 PREFIX = 'wind'
335 PREFIX = 'wind'
365
336
366 def __init__(self):
337 def __init__(self):
367
338
368 self.timerange = 2*60*60
339 self.timerange = 2*60*60
369 self.__isConfig = False
340 self.__isConfig = False
370 self.__nsubplots = 1
341 self.__nsubplots = 1
371
342
372 self.WIDTH = 800
343 self.WIDTH = 800
373 self.HEIGHT = 150
344 self.HEIGHT = 150
374 self.WIDTHPROF = 120
345 self.WIDTHPROF = 120
375 self.HEIGHTPROF = 0
346 self.HEIGHTPROF = 0
376 self.counter_imagwr = 0
347 self.counter_imagwr = 0
377
348
378 self.PLOT_CODE = 0
349 self.PLOT_CODE = WIND_CODE
350
379 self.FTP_WEI = None
351 self.FTP_WEI = None
380 self.EXP_CODE = None
352 self.EXP_CODE = None
381 self.SUB_EXP_CODE = None
353 self.SUB_EXP_CODE = None
382 self.PLOT_POS = None
354 self.PLOT_POS = None
383 self.tmin = None
355 self.tmin = None
384 self.tmax = None
356 self.tmax = None
385
357
386 self.xmin = None
358 self.xmin = None
387 self.xmax = None
359 self.xmax = None
388
360
389 self.figfile = None
361 self.figfile = None
390
362
391 def getSubplots(self):
363 def getSubplots(self):
392
364
393 ncol = 1
365 ncol = 1
394 nrow = self.nplots
366 nrow = self.nplots
395
367
396 return nrow, ncol
368 return nrow, ncol
397
369
398 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
370 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
399
371
400 self.__showprofile = showprofile
372 self.__showprofile = showprofile
401 self.nplots = nplots
373 self.nplots = nplots
402
374
403 ncolspan = 1
375 ncolspan = 1
404 colspan = 1
376 colspan = 1
405
377
406 self.createFigure(id = id,
378 self.createFigure(id = id,
407 wintitle = wintitle,
379 wintitle = wintitle,
408 widthplot = self.WIDTH + self.WIDTHPROF,
380 widthplot = self.WIDTH + self.WIDTHPROF,
409 heightplot = self.HEIGHT + self.HEIGHTPROF,
381 heightplot = self.HEIGHT + self.HEIGHTPROF,
410 show=show)
382 show=show)
411
383
412 nrow, ncol = self.getSubplots()
384 nrow, ncol = self.getSubplots()
413
385
414 counter = 0
386 counter = 0
415 for y in range(nrow):
387 for y in range(nrow):
416 if counter >= self.nplots:
388 if counter >= self.nplots:
417 break
389 break
418
390
419 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
391 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
420 counter += 1
392 counter += 1
421
393
422 def run(self, dataOut, id, wintitle="", channelList=None,
394 def run(self, dataOut, id, wintitle="", channelList=None,
423 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
395 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
424 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
396 zmax_ver = None, zmin_ver = None, SNRmin = None, SNRmax = None,
425 timerange=None, SNRthresh = None,
397 timerange=None, SNRthresh = None,
426 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
398 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
427 server=None, folder=None, username=None, password=None,
399 server=None, folder=None, username=None, password=None,
428 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
400 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
429 """
401 """
430
402
431 Input:
403 Input:
432 dataOut :
404 dataOut :
433 id :
405 id :
434 wintitle :
406 wintitle :
435 channelList :
407 channelList :
436 showProfile :
408 showProfile :
437 xmin : None,
409 xmin : None,
438 xmax : None,
410 xmax : None,
439 ymin : None,
411 ymin : None,
440 ymax : None,
412 ymax : None,
441 zmin : None,
413 zmin : None,
442 zmax : None
414 zmax : None
443 """
415 """
444
416
445 if channelList == None:
417 if channelList == None:
446 channelIndexList = dataOut.channelIndexList
418 channelIndexList = dataOut.channelIndexList
447 else:
419 else:
448 channelIndexList = []
420 channelIndexList = []
449 for channel in channelList:
421 for channel in channelList:
450 if channel not in dataOut.channelList:
422 if channel not in dataOut.channelList:
451 raise ValueError, "Channel %d is not in dataOut.channelList"
423 raise ValueError, "Channel %d is not in dataOut.channelList"
452 channelIndexList.append(dataOut.channelList.index(channel))
424 channelIndexList.append(dataOut.channelList.index(channel))
453
425
454 if timerange != None:
426 if timerange != None:
455 self.timerange = timerange
427 self.timerange = timerange
456
428
457 tmin = None
429 tmin = None
458 tmax = None
430 tmax = None
459
431
460 x = dataOut.getTimeRange1()
432 x = dataOut.getTimeRange1()
461 # y = dataOut.heightList
433 # y = dataOut.heightList
462 y = dataOut.heightList
434 y = dataOut.heightList
463
435
464 z = dataOut.data_output.copy()
436 z = dataOut.data_output.copy()
465 nplots = z.shape[0] #Number of wind dimensions estimated
437 nplots = z.shape[0] #Number of wind dimensions estimated
466 nplotsw = nplots
438 nplotsw = nplots
467
439
468 #If there is a SNR function defined
440 #If there is a SNR function defined
469 if dataOut.data_SNR != None:
441 if dataOut.data_SNR != None:
470 nplots += 1
442 nplots += 1
471 SNR = dataOut.data_SNR
443 SNR = dataOut.data_SNR
472 SNRavg = numpy.average(SNR, axis=0)
444 SNRavg = numpy.average(SNR, axis=0)
473
445
474 SNRdB = 10*numpy.log10(SNR)
446 SNRdB = 10*numpy.log10(SNR)
475 SNRavgdB = 10*numpy.log10(SNRavg)
447 SNRavgdB = 10*numpy.log10(SNRavg)
476
448
477 if SNRthresh == None: SNRthresh = -5.0
449 if SNRthresh == None: SNRthresh = -5.0
478 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
450 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
479
451
480 for i in range(nplotsw):
452 for i in range(nplotsw):
481 z[i,ind] = numpy.nan
453 z[i,ind] = numpy.nan
482
454
483
455
484 showprofile = False
456 showprofile = False
485 # thisDatetime = dataOut.datatime
457 # thisDatetime = dataOut.datatime
486 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
458 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
487 title = wintitle + "Wind"
459 title = wintitle + "Wind"
488 xlabel = ""
460 xlabel = ""
489 ylabel = "Range (Km)"
461 ylabel = "Range (Km)"
490
462
491 if not self.__isConfig:
463 if not self.__isConfig:
492
464
493 self.setup(id=id,
465 self.setup(id=id,
494 nplots=nplots,
466 nplots=nplots,
495 wintitle=wintitle,
467 wintitle=wintitle,
496 showprofile=showprofile,
468 showprofile=showprofile,
497 show=show)
469 show=show)
498
470
499 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
471 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
500
472
501 if ymin == None: ymin = numpy.nanmin(y)
473 if ymin == None: ymin = numpy.nanmin(y)
502 if ymax == None: ymax = numpy.nanmax(y)
474 if ymax == None: ymax = numpy.nanmax(y)
503
475
504 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
476 if zmax == None: zmax = numpy.nanmax(abs(z[range(2),:]))
505 #if numpy.isnan(zmax): zmax = 50
477 #if numpy.isnan(zmax): zmax = 50
506 if zmin == None: zmin = -zmax
478 if zmin == None: zmin = -zmax
507
479
508 if nplotsw == 3:
480 if nplotsw == 3:
509 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
481 if zmax_ver == None: zmax_ver = numpy.nanmax(abs(z[2,:]))
510 if zmin_ver == None: zmin_ver = -zmax_ver
482 if zmin_ver == None: zmin_ver = -zmax_ver
511
483
512 if dataOut.data_SNR != None:
484 if dataOut.data_SNR != None:
513 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
485 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
514 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
486 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
515
487
516 self.FTP_WEI = ftp_wei
488 self.FTP_WEI = ftp_wei
517 self.EXP_CODE = exp_code
489 self.EXP_CODE = exp_code
518 self.SUB_EXP_CODE = sub_exp_code
490 self.SUB_EXP_CODE = sub_exp_code
519 self.PLOT_POS = plot_pos
491 self.PLOT_POS = plot_pos
520
492
521 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
493 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
522 self.__isConfig = True
494 self.__isConfig = True
523
495
524
496
525 self.setWinTitle(title)
497 self.setWinTitle(title)
526
498
527 if ((self.xmax - x[1]) < (x[1]-x[0])):
499 if ((self.xmax - x[1]) < (x[1]-x[0])):
528 x[1] = self.xmax
500 x[1] = self.xmax
529
501
530 strWind = ['Zonal', 'Meridional', 'Vertical']
502 strWind = ['Zonal', 'Meridional', 'Vertical']
531 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
503 strCb = ['Velocity (m/s)','Velocity (m/s)','Velocity (cm/s)']
532 zmaxVector = [zmax, zmax, zmax_ver]
504 zmaxVector = [zmax, zmax, zmax_ver]
533 zminVector = [zmin, zmin, zmin_ver]
505 zminVector = [zmin, zmin, zmin_ver]
534 windFactor = [1,1,100]
506 windFactor = [1,1,100]
535
507
536 for i in range(nplotsw):
508 for i in range(nplotsw):
537
509
538 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
510 title = "%s Wind: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
539 axes = self.axesList[i*self.__nsubplots]
511 axes = self.axesList[i*self.__nsubplots]
540
512
541 z1 = z[i,:].reshape((1,-1))*windFactor[i]
513 z1 = z[i,:].reshape((1,-1))*windFactor[i]
542
514
543 axes.pcolorbuffer(x, y, z1,
515 axes.pcolorbuffer(x, y, z1,
544 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
516 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
545 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
517 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
546 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="RdBu_r" )
518 ticksize=9, cblabel=strCb[i], cbsize="1%", colormap="RdBu_r" )
547
519
548 if dataOut.data_SNR != None:
520 if dataOut.data_SNR != None:
549 i += 1
521 i += 1
550 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
522 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
551 axes = self.axesList[i*self.__nsubplots]
523 axes = self.axesList[i*self.__nsubplots]
552
524
553 SNRavgdB = SNRavgdB.reshape((1,-1))
525 SNRavgdB = SNRavgdB.reshape((1,-1))
554
526
555 axes.pcolorbuffer(x, y, SNRavgdB,
527 axes.pcolorbuffer(x, y, SNRavgdB,
556 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
528 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
557 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
529 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
558 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
530 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
559
531
560 self.draw()
532 self.draw()
561
533
562 if save:
563
564 if self.figfile == None:
565 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
566 self.figfile = self.getFilename(name = str_datetime)
567
568 self.counter_imagwr += 1
569
570 if (self.counter_imagwr>=wr_period):
571 # store png plot to local folder
572 self.saveFigure(figpath, self.figfile)
573 self.counter_imagwr = 0
574
575 if ftp:
576 # store png plot to FTP server according to RT-Web format
577 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
578 ftp_filename = os.path.join(figpath, name)
579 self.saveFigure(figpath, ftp_filename)
580
581
582
583 if x[1] >= self.axesList[0].xmax:
534 if x[1] >= self.axesList[0].xmax:
584 self.counter_imagwr = wr_period
535 self.counter_imagwr = wr_period
585 self.__isConfig = False
536 self.__isConfig = False
586 self.figfile = None
537 self.figfile = None
587
538
539 self.save(figpath=figpath,
540 figfile=figfile,
541 save=save,
542 ftp=ftp,
543 wr_period=wr_period,
544 thisDatetime=thisDatetime,
545 update_figfile=False)
546
588
547
589 class ParametersPlot(Figure):
548 class ParametersPlot(Figure):
590
549
591 __isConfig = None
550 __isConfig = None
592 __nsubplots = None
551 __nsubplots = None
593
552
594 WIDTHPROF = None
553 WIDTHPROF = None
595 HEIGHTPROF = None
554 HEIGHTPROF = None
596 PREFIX = 'prm'
555 PREFIX = 'prm'
597
556
598 def __init__(self):
557 def __init__(self):
599
558
600 self.timerange = 2*60*60
559 self.timerange = 2*60*60
601 self.__isConfig = False
560 self.__isConfig = False
602 self.__nsubplots = 1
561 self.__nsubplots = 1
603
562
604 self.WIDTH = 800
563 self.WIDTH = 800
605 self.HEIGHT = 150
564 self.HEIGHT = 150
606 self.WIDTHPROF = 120
565 self.WIDTHPROF = 120
607 self.HEIGHTPROF = 0
566 self.HEIGHTPROF = 0
608 self.counter_imagwr = 0
567 self.counter_imagwr = 0
609
568
610 self.PLOT_CODE = 0
569 self.PLOT_CODE = PARMS_CODE
570
611 self.FTP_WEI = None
571 self.FTP_WEI = None
612 self.EXP_CODE = None
572 self.EXP_CODE = None
613 self.SUB_EXP_CODE = None
573 self.SUB_EXP_CODE = None
614 self.PLOT_POS = None
574 self.PLOT_POS = None
615 self.tmin = None
575 self.tmin = None
616 self.tmax = None
576 self.tmax = None
617
577
618 self.xmin = None
578 self.xmin = None
619 self.xmax = None
579 self.xmax = None
620
580
621 self.figfile = None
581 self.figfile = None
622
582
623 def getSubplots(self):
583 def getSubplots(self):
624
584
625 ncol = 1
585 ncol = 1
626 nrow = self.nplots
586 nrow = self.nplots
627
587
628 return nrow, ncol
588 return nrow, ncol
629
589
630 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
590 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
631
591
632 self.__showprofile = showprofile
592 self.__showprofile = showprofile
633 self.nplots = nplots
593 self.nplots = nplots
634
594
635 ncolspan = 1
595 ncolspan = 1
636 colspan = 1
596 colspan = 1
637
597
638 self.createFigure(id = id,
598 self.createFigure(id = id,
639 wintitle = wintitle,
599 wintitle = wintitle,
640 widthplot = self.WIDTH + self.WIDTHPROF,
600 widthplot = self.WIDTH + self.WIDTHPROF,
641 heightplot = self.HEIGHT + self.HEIGHTPROF,
601 heightplot = self.HEIGHT + self.HEIGHTPROF,
642 show=show)
602 show=show)
643
603
644 nrow, ncol = self.getSubplots()
604 nrow, ncol = self.getSubplots()
645
605
646 counter = 0
606 counter = 0
647 for y in range(nrow):
607 for y in range(nrow):
648 for x in range(ncol):
608 for x in range(ncol):
649
609
650 if counter >= self.nplots:
610 if counter >= self.nplots:
651 break
611 break
652
612
653 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
613 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
654
614
655 if showprofile:
615 if showprofile:
656 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
616 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
657
617
658 counter += 1
618 counter += 1
659
619
660 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
620 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=False,
661 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
621 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,timerange=None,
662 parameterIndex = None, onlyPositive = False,
622 parameterIndex = None, onlyPositive = False,
663 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None,
623 SNRthresh = -numpy.inf, SNR = True, SNRmin = None, SNRmax = None,
664 zlabel = "", parameterName = "", parameterObject = "data_param",
624 zlabel = "", parameterName = "", parameterObject = "data_param",
665 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
625 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
666 server=None, folder=None, username=None, password=None,
626 server=None, folder=None, username=None, password=None,
667 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
627 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
668
628
669 """
629 """
670
630
671 Input:
631 Input:
672 dataOut :
632 dataOut :
673 id :
633 id :
674 wintitle :
634 wintitle :
675 channelList :
635 channelList :
676 showProfile :
636 showProfile :
677 xmin : None,
637 xmin : None,
678 xmax : None,
638 xmax : None,
679 ymin : None,
639 ymin : None,
680 ymax : None,
640 ymax : None,
681 zmin : None,
641 zmin : None,
682 zmax : None
642 zmax : None
683 """
643 """
684
644
685 data_param = getattr(dataOut, parameterObject)
645 data_param = getattr(dataOut, parameterObject)
686
646
687 if channelList == None:
647 if channelList == None:
688 channelIndexList = numpy.arange(data_param.shape[0])
648 channelIndexList = numpy.arange(data_param.shape[0])
689 else:
649 else:
690 channelIndexList = numpy.array(channelList)
650 channelIndexList = numpy.array(channelList)
691
651
692 nchan = len(channelIndexList) #Number of channels being plotted
652 nchan = len(channelIndexList) #Number of channels being plotted
693
653
694 if timerange != None:
654 if timerange != None:
695 self.timerange = timerange
655 self.timerange = timerange
696
656
697 #tmin = None
657 #tmin = None
698 #tmax = None
658 #tmax = None
699 if parameterIndex == None:
659 if parameterIndex == None:
700 parameterIndex = 1
660 parameterIndex = 1
701 x = dataOut.getTimeRange1()
661 x = dataOut.getTimeRange1()
702 y = dataOut.heightList
662 y = dataOut.heightList
703 z = data_param[channelIndexList,parameterIndex,:].copy()
663 z = data_param[channelIndexList,parameterIndex,:].copy()
704
664
705 zRange = dataOut.abscissaList
665 zRange = dataOut.abscissaList
706 nplots = z.shape[0] #Number of wind dimensions estimated
666 nplots = z.shape[0] #Number of wind dimensions estimated
707 # thisDatetime = dataOut.datatime
667 # thisDatetime = dataOut.datatime
708
668
709 if dataOut.data_SNR != None:
669 if dataOut.data_SNR != None:
710 SNRarray = dataOut.data_SNR[channelIndexList,:]
670 SNRarray = dataOut.data_SNR[channelIndexList,:]
711 SNRdB = 10*numpy.log10(SNRarray)
671 SNRdB = 10*numpy.log10(SNRarray)
712 # SNRavgdB = 10*numpy.log10(SNRavg)
672 # SNRavgdB = 10*numpy.log10(SNRavg)
713 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
673 ind = numpy.where(SNRdB < 10**(SNRthresh/10))
714 z[ind] = numpy.nan
674 z[ind] = numpy.nan
715
675
716 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
676 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
717 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
677 title = wintitle + " Parameters Plot" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
718 xlabel = ""
678 xlabel = ""
719 ylabel = "Range (Km)"
679 ylabel = "Range (Km)"
720
680
721 if SNR: nplots = 2*nplots
681 if SNR: nplots = 2*nplots
722
682
723 if onlyPositive:
683 if onlyPositive:
724 colormap = "jet"
684 colormap = "jet"
725 zmin = 0
685 zmin = 0
726 else: colormap = "RdBu_r"
686 else: colormap = "RdBu_r"
727
687
728 if not self.__isConfig:
688 if not self.__isConfig:
729
689
730 self.setup(id=id,
690 self.setup(id=id,
731 nplots=nplots,
691 nplots=nplots,
732 wintitle=wintitle,
692 wintitle=wintitle,
733 showprofile=showprofile,
693 showprofile=showprofile,
734 show=show)
694 show=show)
735
695
736 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
696 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
737
697
738 if ymin == None: ymin = numpy.nanmin(y)
698 if ymin == None: ymin = numpy.nanmin(y)
739 if ymax == None: ymax = numpy.nanmax(y)
699 if ymax == None: ymax = numpy.nanmax(y)
740 if zmin == None: zmin = numpy.nanmin(zRange)
700 if zmin == None: zmin = numpy.nanmin(zRange)
741 if zmax == None: zmax = numpy.nanmax(zRange)
701 if zmax == None: zmax = numpy.nanmax(zRange)
742
702
743 if SNR != None:
703 if SNR != None:
744 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
704 if SNRmin == None: SNRmin = numpy.nanmin(SNRdB)
745 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
705 if SNRmax == None: SNRmax = numpy.nanmax(SNRdB)
746
706
747 self.FTP_WEI = ftp_wei
707 self.FTP_WEI = ftp_wei
748 self.EXP_CODE = exp_code
708 self.EXP_CODE = exp_code
749 self.SUB_EXP_CODE = sub_exp_code
709 self.SUB_EXP_CODE = sub_exp_code
750 self.PLOT_POS = plot_pos
710 self.PLOT_POS = plot_pos
751
711
752 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
712 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
753 self.__isConfig = True
713 self.__isConfig = True
754 self.figfile = figfile
714 self.figfile = figfile
755
715
756 self.setWinTitle(title)
716 self.setWinTitle(title)
757
717
758 if ((self.xmax - x[1]) < (x[1]-x[0])):
718 if ((self.xmax - x[1]) < (x[1]-x[0])):
759 x[1] = self.xmax
719 x[1] = self.xmax
760
720
761 for i in range(nchan):
721 for i in range(nchan):
762 if SNR: j = 2*i
722 if SNR: j = 2*i
763 else: j = i
723 else: j = i
764
724
765 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i]+1, thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
725 title = "%s Channel %d: %s" %(parameterName, channelIndexList[i]+1, thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
766
726
767 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
727 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
768 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
728 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
769 axes = self.axesList[j*self.__nsubplots]
729 axes = self.axesList[j*self.__nsubplots]
770 z1 = z[i,:].reshape((1,-1))
730 z1 = z[i,:].reshape((1,-1))
771 axes.pcolorbuffer(x, y, z1,
731 axes.pcolorbuffer(x, y, z1,
772 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
732 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
773 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
733 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap=colormap,
774 ticksize=9, cblabel=zlabel, cbsize="1%")
734 ticksize=9, cblabel=zlabel, cbsize="1%")
775
735
776 if SNR:
736 if SNR:
777 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i]+1, thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
737 title = "Channel %d Signal Noise Ratio (SNR): %s" %(channelIndexList[i]+1, thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
778 axes = self.axesList[(j + 1)*self.__nsubplots]
738 axes = self.axesList[(j + 1)*self.__nsubplots]
779 z1 = SNRdB[i,:].reshape((1,-1))
739 z1 = SNRdB[i,:].reshape((1,-1))
780 axes.pcolorbuffer(x, y, z1,
740 axes.pcolorbuffer(x, y, z1,
781 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
741 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
782 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
742 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,colormap="jet",
783 ticksize=9, cblabel=zlabel, cbsize="1%")
743 ticksize=9, cblabel=zlabel, cbsize="1%")
784
744
785
745
786
746
787 self.draw()
747 self.draw()
788
748
789 if save:
790
791 if self.figfile == None:
792 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
793 self.figfile = self.getFilename(name = str_datetime)
794
795 self.counter_imagwr += 1
796
797 if (self.counter_imagwr>=wr_period):
798 # store png plot to local folder
799 self.saveFigure(figpath, self.figfile)
800 self.counter_imagwr = 0
801
802 if ftp:
803 # store png plot to FTP server according to RT-Web format
804 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
805 ftp_filename = os.path.join(figpath, name)
806 self.saveFigure(figpath, ftp_filename)
807
808 if x[1] >= self.axesList[0].xmax:
749 if x[1] >= self.axesList[0].xmax:
809 self.counter_imagwr = wr_period
750 self.counter_imagwr = wr_period
810 self.__isConfig = False
751 self.__isConfig = False
811 self.figfile = None
752 self.figfile = None
812
753
813
754 self.save(figpath=figpath,
755 figfile=figfile,
756 save=save,
757 ftp=ftp,
758 wr_period=wr_period,
759 thisDatetime=thisDatetime,
760 update_figfile=False)
761
814 class SpectralFittingPlot(Figure):
762 class SpectralFittingPlot(Figure):
815
763
816 __isConfig = None
764 __isConfig = None
817 __nsubplots = None
765 __nsubplots = None
818
766
819 WIDTHPROF = None
767 WIDTHPROF = None
820 HEIGHTPROF = None
768 HEIGHTPROF = None
821 PREFIX = 'prm'
769 PREFIX = 'prm'
822
770
823
771
824 N = None
772 N = None
825 ippSeconds = None
773 ippSeconds = None
826
774
827 def __init__(self):
775 def __init__(self):
828 self.__isConfig = False
776 self.__isConfig = False
829 self.__nsubplots = 1
777 self.__nsubplots = 1
830
778
779 self.PLOT_CODE = SPECFIT_CODE
780
831 self.WIDTH = 450
781 self.WIDTH = 450
832 self.HEIGHT = 250
782 self.HEIGHT = 250
833 self.WIDTHPROF = 0
783 self.WIDTHPROF = 0
834 self.HEIGHTPROF = 0
784 self.HEIGHTPROF = 0
835
785
836 def getSubplots(self):
786 def getSubplots(self):
837
787
838 ncol = int(numpy.sqrt(self.nplots)+0.9)
788 ncol = int(numpy.sqrt(self.nplots)+0.9)
839 nrow = int(self.nplots*1./ncol + 0.9)
789 nrow = int(self.nplots*1./ncol + 0.9)
840
790
841 return nrow, ncol
791 return nrow, ncol
842
792
843 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
793 def setup(self, id, nplots, wintitle, showprofile=False, show=True):
844
794
845 showprofile = False
795 showprofile = False
846 self.__showprofile = showprofile
796 self.__showprofile = showprofile
847 self.nplots = nplots
797 self.nplots = nplots
848
798
849 ncolspan = 5
799 ncolspan = 5
850 colspan = 4
800 colspan = 4
851 if showprofile:
801 if showprofile:
852 ncolspan = 5
802 ncolspan = 5
853 colspan = 4
803 colspan = 4
854 self.__nsubplots = 2
804 self.__nsubplots = 2
855
805
856 self.createFigure(id = id,
806 self.createFigure(id = id,
857 wintitle = wintitle,
807 wintitle = wintitle,
858 widthplot = self.WIDTH + self.WIDTHPROF,
808 widthplot = self.WIDTH + self.WIDTHPROF,
859 heightplot = self.HEIGHT + self.HEIGHTPROF,
809 heightplot = self.HEIGHT + self.HEIGHTPROF,
860 show=show)
810 show=show)
861
811
862 nrow, ncol = self.getSubplots()
812 nrow, ncol = self.getSubplots()
863
813
864 counter = 0
814 counter = 0
865 for y in range(nrow):
815 for y in range(nrow):
866 for x in range(ncol):
816 for x in range(ncol):
867
817
868 if counter >= self.nplots:
818 if counter >= self.nplots:
869 break
819 break
870
820
871 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
821 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
872
822
873 if showprofile:
823 if showprofile:
874 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
824 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
875
825
876 counter += 1
826 counter += 1
877
827
878 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
828 def run(self, dataOut, id, cutHeight=None, fit=False, wintitle="", channelList=None, showprofile=True,
879 xmin=None, xmax=None, ymin=None, ymax=None,
829 xmin=None, xmax=None, ymin=None, ymax=None,
880 save=False, figpath='./', figfile=None, show=True):
830 save=False, figpath='./', figfile=None, show=True):
881
831
882 """
832 """
883
833
884 Input:
834 Input:
885 dataOut :
835 dataOut :
886 id :
836 id :
887 wintitle :
837 wintitle :
888 channelList :
838 channelList :
889 showProfile :
839 showProfile :
890 xmin : None,
840 xmin : None,
891 xmax : None,
841 xmax : None,
892 zmin : None,
842 zmin : None,
893 zmax : None
843 zmax : None
894 """
844 """
895
845
896 if cutHeight==None:
846 if cutHeight==None:
897 h=270
847 h=270
898 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
848 heightindex = numpy.abs(cutHeight - dataOut.heightList).argmin()
899 cutHeight = dataOut.heightList[heightindex]
849 cutHeight = dataOut.heightList[heightindex]
900
850
901 factor = dataOut.normFactor
851 factor = dataOut.normFactor
902 x = dataOut.abscissaList[:-1]
852 x = dataOut.abscissaList[:-1]
903 #y = dataOut.getHeiRange()
853 #y = dataOut.getHeiRange()
904
854
905 z = dataOut.data_pre[:,:,heightindex]/factor
855 z = dataOut.data_pre[:,:,heightindex]/factor
906 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
856 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
907 avg = numpy.average(z, axis=1)
857 avg = numpy.average(z, axis=1)
908 listChannels = z.shape[0]
858 listChannels = z.shape[0]
909
859
910 #Reconstruct Function
860 #Reconstruct Function
911 if fit==True:
861 if fit==True:
912 groupArray = dataOut.groupList
862 groupArray = dataOut.groupList
913 listChannels = groupArray.reshape((groupArray.size))
863 listChannels = groupArray.reshape((groupArray.size))
914 listChannels.sort()
864 listChannels.sort()
915 spcFitLine = numpy.zeros(z.shape)
865 spcFitLine = numpy.zeros(z.shape)
916 constants = dataOut.constants
866 constants = dataOut.constants
917
867
918 nGroups = groupArray.shape[0]
868 nGroups = groupArray.shape[0]
919 nChannels = groupArray.shape[1]
869 nChannels = groupArray.shape[1]
920 nProfiles = z.shape[1]
870 nProfiles = z.shape[1]
921
871
922 for f in range(nGroups):
872 for f in range(nGroups):
923 groupChann = groupArray[f,:]
873 groupChann = groupArray[f,:]
924 p = dataOut.data_param[f,:,heightindex]
874 p = dataOut.data_param[f,:,heightindex]
925 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
875 # p = numpy.array([ 89.343967,0.14036615,0.17086219,18.89835291,1.58388365,1.55099167])
926 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
876 fitLineAux = dataOut.library.modelFunction(p, constants)*nProfiles
927 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
877 fitLineAux = fitLineAux.reshape((nChannels,nProfiles))
928 spcFitLine[groupChann,:] = fitLineAux
878 spcFitLine[groupChann,:] = fitLineAux
929 # spcFitLine = spcFitLine/factor
879 # spcFitLine = spcFitLine/factor
930
880
931 z = z[listChannels,:]
881 z = z[listChannels,:]
932 spcFitLine = spcFitLine[listChannels,:]
882 spcFitLine = spcFitLine[listChannels,:]
933 spcFitLinedB = 10*numpy.log10(spcFitLine)
883 spcFitLinedB = 10*numpy.log10(spcFitLine)
934
884
935 zdB = 10*numpy.log10(z)
885 zdB = 10*numpy.log10(z)
936 #thisDatetime = dataOut.datatime
886 #thisDatetime = dataOut.datatime
937 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
887 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
938 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
888 title = wintitle + " Doppler Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
939 xlabel = "Velocity (m/s)"
889 xlabel = "Velocity (m/s)"
940 ylabel = "Spectrum"
890 ylabel = "Spectrum"
941
891
942 if not self.__isConfig:
892 if not self.__isConfig:
943
893
944 nplots = listChannels.size
894 nplots = listChannels.size
945
895
946 self.setup(id=id,
896 self.setup(id=id,
947 nplots=nplots,
897 nplots=nplots,
948 wintitle=wintitle,
898 wintitle=wintitle,
949 showprofile=showprofile,
899 showprofile=showprofile,
950 show=show)
900 show=show)
951
901
952 if xmin == None: xmin = numpy.nanmin(x)
902 if xmin == None: xmin = numpy.nanmin(x)
953 if xmax == None: xmax = numpy.nanmax(x)
903 if xmax == None: xmax = numpy.nanmax(x)
954 if ymin == None: ymin = numpy.nanmin(zdB)
904 if ymin == None: ymin = numpy.nanmin(zdB)
955 if ymax == None: ymax = numpy.nanmax(zdB)+2
905 if ymax == None: ymax = numpy.nanmax(zdB)+2
956
906
957 self.__isConfig = True
907 self.__isConfig = True
958
908
959 self.setWinTitle(title)
909 self.setWinTitle(title)
960 for i in range(self.nplots):
910 for i in range(self.nplots):
961 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
911 # title = "Channel %d: %4.2fdB" %(dataOut.channelList[i]+1, noisedB[i])
962 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i]+1)
912 title = "Height %4.1f km\nChannel %d:" %(cutHeight, listChannels[i]+1)
963 axes = self.axesList[i*self.__nsubplots]
913 axes = self.axesList[i*self.__nsubplots]
964 if fit == False:
914 if fit == False:
965 axes.pline(x, zdB[i,:],
915 axes.pline(x, zdB[i,:],
966 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
916 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
967 xlabel=xlabel, ylabel=ylabel, title=title
917 xlabel=xlabel, ylabel=ylabel, title=title
968 )
918 )
969 if fit == True:
919 if fit == True:
970 fitline=spcFitLinedB[i,:]
920 fitline=spcFitLinedB[i,:]
971 y=numpy.vstack([zdB[i,:],fitline] )
921 y=numpy.vstack([zdB[i,:],fitline] )
972 legendlabels=['Data','Fitting']
922 legendlabels=['Data','Fitting']
973 axes.pmultilineyaxis(x, y,
923 axes.pmultilineyaxis(x, y,
974 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
924 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
975 xlabel=xlabel, ylabel=ylabel, title=title,
925 xlabel=xlabel, ylabel=ylabel, title=title,
976 legendlabels=legendlabels, marker=None,
926 legendlabels=legendlabels, marker=None,
977 linestyle='solid', grid='both')
927 linestyle='solid', grid='both')
978
928
979 self.draw()
929 self.draw()
980
930
981 if save:
931 self.save(figpath=figpath,
982 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
932 figfile=figfile,
983 if figfile == None:
933 save=save,
984 figfile = self.getFilename(name = date)
934 ftp=ftp,
985
935 wr_period=wr_period,
986 self.saveFigure(figpath, figfile)
936 thisDatetime=thisDatetime)
987
937
988
938
989 class EWDriftsPlot(Figure):
939 class EWDriftsPlot(Figure):
990
940
991 __isConfig = None
941 __isConfig = None
992 __nsubplots = None
942 __nsubplots = None
993
943
994 WIDTHPROF = None
944 WIDTHPROF = None
995 HEIGHTPROF = None
945 HEIGHTPROF = None
996 PREFIX = 'drift'
946 PREFIX = 'drift'
997
947
998 def __init__(self):
948 def __init__(self):
999
949
1000 self.timerange = 2*60*60
950 self.timerange = 2*60*60
1001 self.isConfig = False
951 self.isConfig = False
1002 self.__nsubplots = 1
952 self.__nsubplots = 1
1003
953
1004 self.WIDTH = 800
954 self.WIDTH = 800
1005 self.HEIGHT = 150
955 self.HEIGHT = 150
1006 self.WIDTHPROF = 120
956 self.WIDTHPROF = 120
1007 self.HEIGHTPROF = 0
957 self.HEIGHTPROF = 0
1008 self.counter_imagwr = 0
958 self.counter_imagwr = 0
1009
959
1010 self.PLOT_CODE = 0
960 self.PLOT_CODE = EWDRIFT_CODE
961
1011 self.FTP_WEI = None
962 self.FTP_WEI = None
1012 self.EXP_CODE = None
963 self.EXP_CODE = None
1013 self.SUB_EXP_CODE = None
964 self.SUB_EXP_CODE = None
1014 self.PLOT_POS = None
965 self.PLOT_POS = None
1015 self.tmin = None
966 self.tmin = None
1016 self.tmax = None
967 self.tmax = None
1017
968
1018 self.xmin = None
969 self.xmin = None
1019 self.xmax = None
970 self.xmax = None
1020
971
1021 self.figfile = None
972 self.figfile = None
1022
973
1023 def getSubplots(self):
974 def getSubplots(self):
1024
975
1025 ncol = 1
976 ncol = 1
1026 nrow = self.nplots
977 nrow = self.nplots
1027
978
1028 return nrow, ncol
979 return nrow, ncol
1029
980
1030 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
981 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1031
982
1032 self.__showprofile = showprofile
983 self.__showprofile = showprofile
1033 self.nplots = nplots
984 self.nplots = nplots
1034
985
1035 ncolspan = 1
986 ncolspan = 1
1036 colspan = 1
987 colspan = 1
1037
988
1038 self.createFigure(id = id,
989 self.createFigure(id = id,
1039 wintitle = wintitle,
990 wintitle = wintitle,
1040 widthplot = self.WIDTH + self.WIDTHPROF,
991 widthplot = self.WIDTH + self.WIDTHPROF,
1041 heightplot = self.HEIGHT + self.HEIGHTPROF,
992 heightplot = self.HEIGHT + self.HEIGHTPROF,
1042 show=show)
993 show=show)
1043
994
1044 nrow, ncol = self.getSubplots()
995 nrow, ncol = self.getSubplots()
1045
996
1046 counter = 0
997 counter = 0
1047 for y in range(nrow):
998 for y in range(nrow):
1048 if counter >= self.nplots:
999 if counter >= self.nplots:
1049 break
1000 break
1050
1001
1051 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1002 self.addAxes(nrow, ncol*ncolspan, y, 0, colspan, 1)
1052 counter += 1
1003 counter += 1
1053
1004
1054 def run(self, dataOut, id, wintitle="", channelList=None,
1005 def run(self, dataOut, id, wintitle="", channelList=None,
1055 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1006 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
1056 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1007 zmaxVertical = None, zminVertical = None, zmaxZonal = None, zminZonal = None,
1057 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1008 timerange=None, SNRthresh = -numpy.inf, SNRmin = None, SNRmax = None, SNR_1 = False,
1058 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1009 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
1059 server=None, folder=None, username=None, password=None,
1010 server=None, folder=None, username=None, password=None,
1060 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1011 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1061 """
1012 """
1062
1013
1063 Input:
1014 Input:
1064 dataOut :
1015 dataOut :
1065 id :
1016 id :
1066 wintitle :
1017 wintitle :
1067 channelList :
1018 channelList :
1068 showProfile :
1019 showProfile :
1069 xmin : None,
1020 xmin : None,
1070 xmax : None,
1021 xmax : None,
1071 ymin : None,
1022 ymin : None,
1072 ymax : None,
1023 ymax : None,
1073 zmin : None,
1024 zmin : None,
1074 zmax : None
1025 zmax : None
1075 """
1026 """
1076
1027
1077 if timerange != None:
1028 if timerange != None:
1078 self.timerange = timerange
1029 self.timerange = timerange
1079
1030
1080 tmin = None
1031 tmin = None
1081 tmax = None
1032 tmax = None
1082
1033
1083 x = dataOut.getTimeRange1()
1034 x = dataOut.getTimeRange1()
1084 # y = dataOut.heightList
1035 # y = dataOut.heightList
1085 y = dataOut.heightList
1036 y = dataOut.heightList
1086
1037
1087 z = dataOut.data_output
1038 z = dataOut.data_output
1088 nplots = z.shape[0] #Number of wind dimensions estimated
1039 nplots = z.shape[0] #Number of wind dimensions estimated
1089 nplotsw = nplots
1040 nplotsw = nplots
1090
1041
1091 #If there is a SNR function defined
1042 #If there is a SNR function defined
1092 if dataOut.data_SNR != None:
1043 if dataOut.data_SNR != None:
1093 nplots += 1
1044 nplots += 1
1094 SNR = dataOut.data_SNR
1045 SNR = dataOut.data_SNR
1095
1046
1096 if SNR_1:
1047 if SNR_1:
1097 SNR += 1
1048 SNR += 1
1098
1049
1099 SNRavg = numpy.average(SNR, axis=0)
1050 SNRavg = numpy.average(SNR, axis=0)
1100
1051
1101 SNRdB = 10*numpy.log10(SNR)
1052 SNRdB = 10*numpy.log10(SNR)
1102 SNRavgdB = 10*numpy.log10(SNRavg)
1053 SNRavgdB = 10*numpy.log10(SNRavg)
1103
1054
1104 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1055 ind = numpy.where(SNRavg < 10**(SNRthresh/10))[0]
1105
1056
1106 for i in range(nplotsw):
1057 for i in range(nplotsw):
1107 z[i,ind] = numpy.nan
1058 z[i,ind] = numpy.nan
1108
1059
1109
1060
1110 showprofile = False
1061 showprofile = False
1111 # thisDatetime = dataOut.datatime
1062 # thisDatetime = dataOut.datatime
1112 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1063 thisDatetime = datetime.datetime.utcfromtimestamp(x[1])
1113 title = wintitle + " EW Drifts"
1064 title = wintitle + " EW Drifts"
1114 xlabel = ""
1065 xlabel = ""
1115 ylabel = "Height (Km)"
1066 ylabel = "Height (Km)"
1116
1067
1117 if not self.__isConfig:
1068 if not self.__isConfig:
1118
1069
1119 self.setup(id=id,
1070 self.setup(id=id,
1120 nplots=nplots,
1071 nplots=nplots,
1121 wintitle=wintitle,
1072 wintitle=wintitle,
1122 showprofile=showprofile,
1073 showprofile=showprofile,
1123 show=show)
1074 show=show)
1124
1075
1125 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1076 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1126
1077
1127 if ymin == None: ymin = numpy.nanmin(y)
1078 if ymin == None: ymin = numpy.nanmin(y)
1128 if ymax == None: ymax = numpy.nanmax(y)
1079 if ymax == None: ymax = numpy.nanmax(y)
1129
1080
1130 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1081 if zmaxZonal == None: zmaxZonal = numpy.nanmax(abs(z[0,:]))
1131 if zminZonal == None: zminZonal = -zmaxZonal
1082 if zminZonal == None: zminZonal = -zmaxZonal
1132 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1083 if zmaxVertical == None: zmaxVertical = numpy.nanmax(abs(z[1,:]))
1133 if zminVertical == None: zminVertical = -zmaxVertical
1084 if zminVertical == None: zminVertical = -zmaxVertical
1134
1085
1135 if dataOut.data_SNR != None:
1086 if dataOut.data_SNR != None:
1136 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1087 if SNRmin == None: SNRmin = numpy.nanmin(SNRavgdB)
1137 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1088 if SNRmax == None: SNRmax = numpy.nanmax(SNRavgdB)
1138
1089
1139 self.FTP_WEI = ftp_wei
1090 self.FTP_WEI = ftp_wei
1140 self.EXP_CODE = exp_code
1091 self.EXP_CODE = exp_code
1141 self.SUB_EXP_CODE = sub_exp_code
1092 self.SUB_EXP_CODE = sub_exp_code
1142 self.PLOT_POS = plot_pos
1093 self.PLOT_POS = plot_pos
1143
1094
1144 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1095 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1145 self.__isConfig = True
1096 self.__isConfig = True
1146
1097
1147
1098
1148 self.setWinTitle(title)
1099 self.setWinTitle(title)
1149
1100
1150 if ((self.xmax - x[1]) < (x[1]-x[0])):
1101 if ((self.xmax - x[1]) < (x[1]-x[0])):
1151 x[1] = self.xmax
1102 x[1] = self.xmax
1152
1103
1153 strWind = ['Zonal','Vertical']
1104 strWind = ['Zonal','Vertical']
1154 strCb = 'Velocity (m/s)'
1105 strCb = 'Velocity (m/s)'
1155 zmaxVector = [zmaxZonal, zmaxVertical]
1106 zmaxVector = [zmaxZonal, zmaxVertical]
1156 zminVector = [zminZonal, zminVertical]
1107 zminVector = [zminZonal, zminVertical]
1157
1108
1158 for i in range(nplotsw):
1109 for i in range(nplotsw):
1159
1110
1160 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1111 title = "%s Drifts: %s" %(strWind[i], thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1161 axes = self.axesList[i*self.__nsubplots]
1112 axes = self.axesList[i*self.__nsubplots]
1162
1113
1163 z1 = z[i,:].reshape((1,-1))
1114 z1 = z[i,:].reshape((1,-1))
1164
1115
1165 axes.pcolorbuffer(x, y, z1,
1116 axes.pcolorbuffer(x, y, z1,
1166 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1117 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zminVector[i], zmax=zmaxVector[i],
1167 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1118 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1168 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1119 ticksize=9, cblabel=strCb, cbsize="1%", colormap="RdBu_r")
1169
1120
1170 if dataOut.data_SNR != None:
1121 if dataOut.data_SNR != None:
1171 i += 1
1122 i += 1
1172 if SNR_1:
1123 if SNR_1:
1173 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1124 title = "Signal Noise Ratio + 1 (SNR+1): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1174 else:
1125 else:
1175 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1126 title = "Signal Noise Ratio (SNR): %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1176 axes = self.axesList[i*self.__nsubplots]
1127 axes = self.axesList[i*self.__nsubplots]
1177 SNRavgdB = SNRavgdB.reshape((1,-1))
1128 SNRavgdB = SNRavgdB.reshape((1,-1))
1178
1129
1179 axes.pcolorbuffer(x, y, SNRavgdB,
1130 axes.pcolorbuffer(x, y, SNRavgdB,
1180 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1131 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=SNRmin, zmax=SNRmax,
1181 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1132 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
1182 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1133 ticksize=9, cblabel='', cbsize="1%", colormap="jet")
1183
1134
1184 self.draw()
1135 self.draw()
1185
1136
1186 if save:
1187
1188 if self.figfile == None:
1189 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1190 self.figfile = self.getFilename(name = str_datetime)
1191
1192 self.counter_imagwr += 1
1193
1194 if (self.counter_imagwr>=wr_period):
1195 # store png plot to local folder
1196 self.saveFigure(figpath, self.figfile)
1197 self.counter_imagwr = 0
1198
1199 if ftp:
1200 # store png plot to FTP server according to RT-Web format
1201 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
1202 ftp_filename = os.path.join(figpath, name)
1203 self.saveFigure(figpath, ftp_filename)
1204
1205 if x[1] >= self.axesList[0].xmax:
1137 if x[1] >= self.axesList[0].xmax:
1206 self.counter_imagwr = wr_period
1138 self.counter_imagwr = wr_period
1207 self.__isConfig = False
1139 self.__isConfig = False
1208 self.figfile = None No newline at end of file
1140 self.figfile = None
1141
1142 self.save(figpath=figpath,
1143 figfile=figfile,
1144 save=save,
1145 ftp=ftp,
1146 wr_period=wr_period,
1147 thisDatetime=thisDatetime,
1148 update_figfile=False) No newline at end of file
@@ -1,1375 +1,1314
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from figure import Figure, isRealtime
10 from figure import Figure, isRealtime
11 from plotting_codes import *
11
12
12 class SpectraPlot(Figure):
13 class SpectraPlot(Figure):
13
14
14 isConfig = None
15 isConfig = None
15 __nsubplots = None
16 __nsubplots = None
16
17
17 WIDTHPROF = None
18 WIDTHPROF = None
18 HEIGHTPROF = None
19 HEIGHTPROF = None
19 PREFIX = 'spc'
20 PREFIX = 'spc'
20
21
21 def __init__(self):
22 def __init__(self):
22
23
23 self.isConfig = False
24 self.isConfig = False
24 self.__nsubplots = 1
25 self.__nsubplots = 1
25
26
26 self.WIDTH = 280
27 self.WIDTH = 280
27 self.HEIGHT = 250
28 self.HEIGHT = 250
28 self.WIDTHPROF = 120
29 self.WIDTHPROF = 120
29 self.HEIGHTPROF = 0
30 self.HEIGHTPROF = 0
30 self.counter_imagwr = 0
31 self.counter_imagwr = 0
31
32
32 self.PLOT_CODE = 1
33 self.PLOT_CODE = SPEC_CODE
34
33 self.FTP_WEI = None
35 self.FTP_WEI = None
34 self.EXP_CODE = None
36 self.EXP_CODE = None
35 self.SUB_EXP_CODE = None
37 self.SUB_EXP_CODE = None
36 self.PLOT_POS = None
38 self.PLOT_POS = None
37
39
38 self.__xfilter_ena = False
40 self.__xfilter_ena = False
39 self.__yfilter_ena = False
41 self.__yfilter_ena = False
40
42
41 def getSubplots(self):
43 def getSubplots(self):
42
44
43 ncol = int(numpy.sqrt(self.nplots)+0.9)
45 ncol = int(numpy.sqrt(self.nplots)+0.9)
44 nrow = int(self.nplots*1./ncol + 0.9)
46 nrow = int(self.nplots*1./ncol + 0.9)
45
47
46 return nrow, ncol
48 return nrow, ncol
47
49
48 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
50 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
49
51
50 self.__showprofile = showprofile
52 self.__showprofile = showprofile
51 self.nplots = nplots
53 self.nplots = nplots
52
54
53 ncolspan = 1
55 ncolspan = 1
54 colspan = 1
56 colspan = 1
55 if showprofile:
57 if showprofile:
56 ncolspan = 3
58 ncolspan = 3
57 colspan = 2
59 colspan = 2
58 self.__nsubplots = 2
60 self.__nsubplots = 2
59
61
60 self.createFigure(id = id,
62 self.createFigure(id = id,
61 wintitle = wintitle,
63 wintitle = wintitle,
62 widthplot = self.WIDTH + self.WIDTHPROF,
64 widthplot = self.WIDTH + self.WIDTHPROF,
63 heightplot = self.HEIGHT + self.HEIGHTPROF,
65 heightplot = self.HEIGHT + self.HEIGHTPROF,
64 show=show)
66 show=show)
65
67
66 nrow, ncol = self.getSubplots()
68 nrow, ncol = self.getSubplots()
67
69
68 counter = 0
70 counter = 0
69 for y in range(nrow):
71 for y in range(nrow):
70 for x in range(ncol):
72 for x in range(ncol):
71
73
72 if counter >= self.nplots:
74 if counter >= self.nplots:
73 break
75 break
74
76
75 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
77 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
76
78
77 if showprofile:
79 if showprofile:
78 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
80 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
79
81
80 counter += 1
82 counter += 1
81
83
82 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
84 def run(self, dataOut, id, wintitle="", channelList=None, showprofile=True,
83 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
85 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
84 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
86 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
85 server=None, folder=None, username=None, password=None,
87 server=None, folder=None, username=None, password=None,
86 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
88 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0, realtime=False):
87
89
88 """
90 """
89
91
90 Input:
92 Input:
91 dataOut :
93 dataOut :
92 id :
94 id :
93 wintitle :
95 wintitle :
94 channelList :
96 channelList :
95 showProfile :
97 showProfile :
96 xmin : None,
98 xmin : None,
97 xmax : None,
99 xmax : None,
98 ymin : None,
100 ymin : None,
99 ymax : None,
101 ymax : None,
100 zmin : None,
102 zmin : None,
101 zmax : None
103 zmax : None
102 """
104 """
103
105
104 if realtime:
106 if realtime:
105 if not(isRealtime(utcdatatime = dataOut.utctime)):
107 if not(isRealtime(utcdatatime = dataOut.utctime)):
106 print 'Skipping this plot function'
108 print 'Skipping this plot function'
107 return
109 return
108
110
109 if channelList == None:
111 if channelList == None:
110 channelIndexList = dataOut.channelIndexList
112 channelIndexList = dataOut.channelIndexList
111 else:
113 else:
112 channelIndexList = []
114 channelIndexList = []
113 for channel in channelList:
115 for channel in channelList:
114 if channel not in dataOut.channelList:
116 if channel not in dataOut.channelList:
115 raise ValueError, "Channel %d is not in dataOut.channelList"
117 raise ValueError, "Channel %d is not in dataOut.channelList"
116 channelIndexList.append(dataOut.channelList.index(channel))
118 channelIndexList.append(dataOut.channelList.index(channel))
117
119
118 factor = dataOut.normFactor
120 factor = dataOut.normFactor
119
121
120 x = dataOut.getVelRange(1)
122 x = dataOut.getVelRange(1)
121 y = dataOut.getHeiRange()
123 y = dataOut.getHeiRange()
122
124
123 z = dataOut.data_spc[channelIndexList,:,:]/factor
125 z = dataOut.data_spc[channelIndexList,:,:]/factor
124 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
126 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
125 zdB = 10*numpy.log10(z)
127 zdB = 10*numpy.log10(z)
126
128
127 avg = numpy.nanmean(z, axis=1)
129 avg = numpy.nanmean(z, axis=1)
128 avgdB = 10*numpy.log10(avg)
130 avgdB = 10*numpy.log10(avg)
129
131
130 noise = dataOut.getNoise()/factor
132 noise = dataOut.getNoise()/factor
131 noisedB = 10*numpy.log10(noise)
133 noisedB = 10*numpy.log10(noise)
132
134
133 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
135 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
134 title = wintitle + " Spectra"
136 title = wintitle + " Spectra"
135 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
137 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
136 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
138 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
137
139
138 xlabel = "Velocity (m/s)"
140 xlabel = "Velocity (m/s)"
139 ylabel = "Range (Km)"
141 ylabel = "Range (Km)"
140
142
141 if not self.isConfig:
143 if not self.isConfig:
142
144
143 nplots = len(channelIndexList)
145 nplots = len(channelIndexList)
144
146
145 self.setup(id=id,
147 self.setup(id=id,
146 nplots=nplots,
148 nplots=nplots,
147 wintitle=wintitle,
149 wintitle=wintitle,
148 showprofile=showprofile,
150 showprofile=showprofile,
149 show=show)
151 show=show)
150
152
151 if xmin == None: xmin = numpy.nanmin(x)
153 if xmin == None: xmin = numpy.nanmin(x)
152 if xmax == None: xmax = numpy.nanmax(x)
154 if xmax == None: xmax = numpy.nanmax(x)
153 if ymin == None: ymin = numpy.nanmin(y)
155 if ymin == None: ymin = numpy.nanmin(y)
154 if ymax == None: ymax = numpy.nanmax(y)
156 if ymax == None: ymax = numpy.nanmax(y)
155 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
157 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
156 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
158 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
157
159
158 self.FTP_WEI = ftp_wei
160 self.FTP_WEI = ftp_wei
159 self.EXP_CODE = exp_code
161 self.EXP_CODE = exp_code
160 self.SUB_EXP_CODE = sub_exp_code
162 self.SUB_EXP_CODE = sub_exp_code
161 self.PLOT_POS = plot_pos
163 self.PLOT_POS = plot_pos
162
164
163 self.isConfig = True
165 self.isConfig = True
164
166
165 self.setWinTitle(title)
167 self.setWinTitle(title)
166
168
167 for i in range(self.nplots):
169 for i in range(self.nplots):
168 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
170 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
169 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i]+1, noisedB[i], str_datetime)
171 title = "Channel %d: %4.2fdB: %s" %(dataOut.channelList[i]+1, noisedB[i], str_datetime)
170 if len(dataOut.beam.codeList) != 0:
172 if len(dataOut.beam.codeList) != 0:
171 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[i]+1, noisedB[i], dataOut.beam.azimuthList[i], dataOut.beam.zenithList[i], str_datetime)
173 title = "Ch%d:%4.2fdB,%2.2f,%2.2f:%s" %(dataOut.channelList[i]+1, noisedB[i], dataOut.beam.azimuthList[i], dataOut.beam.zenithList[i], str_datetime)
172
174
173 axes = self.axesList[i*self.__nsubplots]
175 axes = self.axesList[i*self.__nsubplots]
174 axes.pcolor(x, y, zdB[i,:,:],
176 axes.pcolor(x, y, zdB[i,:,:],
175 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
177 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
176 xlabel=xlabel, ylabel=ylabel, title=title,
178 xlabel=xlabel, ylabel=ylabel, title=title,
177 ticksize=9, cblabel='')
179 ticksize=9, cblabel='')
178
180
179 if self.__showprofile:
181 if self.__showprofile:
180 axes = self.axesList[i*self.__nsubplots +1]
182 axes = self.axesList[i*self.__nsubplots +1]
181 axes.pline(avgdB[i,:], y,
183 axes.pline(avgdB[i,:], y,
182 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
184 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
183 xlabel='dB', ylabel='', title='',
185 xlabel='dB', ylabel='', title='',
184 ytick_visible=False,
186 ytick_visible=False,
185 grid='x')
187 grid='x')
186
188
187 noiseline = numpy.repeat(noisedB[i], len(y))
189 noiseline = numpy.repeat(noisedB[i], len(y))
188 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
190 axes.addpline(noiseline, y, idline=1, color="black", linestyle="dashed", lw=2)
189
191
190 self.draw()
192 self.draw()
191
193
192 if save:
194 if figfile == None:
193
195 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
194 if figfile == None:
196 name = str_datetime
195 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
197 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
196 figfile = self.getFilename(name = str_datetime)
198 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
197 name = str_datetime
199 figfile = self.getFilename(name)
198 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
199 name = name + '_az' + '_%2.2f'%(dataOut.azimuth) + '_zn' + '_%2.2f'%(dataOut.zenith)
200 figfile = self.getFilename(name)
201
202 self.counter_imagwr += 1
203
204 if (self.counter_imagwr>=wr_period):
205 # store png plot to local folder
206 self.saveFigure(figpath, figfile)
207 self.counter_imagwr = 0
208
200
209 if ftp:
201 self.save(figpath=figpath,
210 # store png plot to FTP server according to RT-Web format
202 figfile=figfile,
211 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
203 save=save,
212 ftp_filename = os.path.join(figpath, name)
204 ftp=ftp,
213 self.saveFigure(figpath, ftp_filename)
205 wr_period=wr_period,
214
206 thisDatetime=thisDatetime)
215
216
207
217 class CrossSpectraPlot(Figure):
208 class CrossSpectraPlot(Figure):
218
209
219 isConfig = None
210 isConfig = None
220 __nsubplots = None
211 __nsubplots = None
221
212
222 WIDTH = None
213 WIDTH = None
223 HEIGHT = None
214 HEIGHT = None
224 WIDTHPROF = None
215 WIDTHPROF = None
225 HEIGHTPROF = None
216 HEIGHTPROF = None
226 PREFIX = 'cspc'
217 PREFIX = 'cspc'
227
218
228 def __init__(self):
219 def __init__(self):
229
220
230 self.isConfig = False
221 self.isConfig = False
231 self.__nsubplots = 4
222 self.__nsubplots = 4
232 self.counter_imagwr = 0
223 self.counter_imagwr = 0
233 self.WIDTH = 250
224 self.WIDTH = 250
234 self.HEIGHT = 250
225 self.HEIGHT = 250
235 self.WIDTHPROF = 0
226 self.WIDTHPROF = 0
236 self.HEIGHTPROF = 0
227 self.HEIGHTPROF = 0
237
228
238 self.PLOT_CODE = 1
229 self.PLOT_CODE = CROSS_CODE
239 self.FTP_WEI = None
230 self.FTP_WEI = None
240 self.EXP_CODE = None
231 self.EXP_CODE = None
241 self.SUB_EXP_CODE = None
232 self.SUB_EXP_CODE = None
242 self.PLOT_POS = None
233 self.PLOT_POS = None
243
234
244 def getSubplots(self):
235 def getSubplots(self):
245
236
246 ncol = 4
237 ncol = 4
247 nrow = self.nplots
238 nrow = self.nplots
248
239
249 return nrow, ncol
240 return nrow, ncol
250
241
251 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
242 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
252
243
253 self.__showprofile = showprofile
244 self.__showprofile = showprofile
254 self.nplots = nplots
245 self.nplots = nplots
255
246
256 ncolspan = 1
247 ncolspan = 1
257 colspan = 1
248 colspan = 1
258
249
259 self.createFigure(id = id,
250 self.createFigure(id = id,
260 wintitle = wintitle,
251 wintitle = wintitle,
261 widthplot = self.WIDTH + self.WIDTHPROF,
252 widthplot = self.WIDTH + self.WIDTHPROF,
262 heightplot = self.HEIGHT + self.HEIGHTPROF,
253 heightplot = self.HEIGHT + self.HEIGHTPROF,
263 show=True)
254 show=True)
264
255
265 nrow, ncol = self.getSubplots()
256 nrow, ncol = self.getSubplots()
266
257
267 counter = 0
258 counter = 0
268 for y in range(nrow):
259 for y in range(nrow):
269 for x in range(ncol):
260 for x in range(ncol):
270 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
261 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
271
262
272 counter += 1
263 counter += 1
273
264
274 def run(self, dataOut, id, wintitle="", pairsList=None,
265 def run(self, dataOut, id, wintitle="", pairsList=None,
275 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
266 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
276 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
267 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
277 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
268 power_cmap='jet', coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
278 server=None, folder=None, username=None, password=None,
269 server=None, folder=None, username=None, password=None,
279 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
270 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
280
271
281 """
272 """
282
273
283 Input:
274 Input:
284 dataOut :
275 dataOut :
285 id :
276 id :
286 wintitle :
277 wintitle :
287 channelList :
278 channelList :
288 showProfile :
279 showProfile :
289 xmin : None,
280 xmin : None,
290 xmax : None,
281 xmax : None,
291 ymin : None,
282 ymin : None,
292 ymax : None,
283 ymax : None,
293 zmin : None,
284 zmin : None,
294 zmax : None
285 zmax : None
295 """
286 """
296
287
297 if pairsList == None:
288 if pairsList == None:
298 pairsIndexList = dataOut.pairsIndexList
289 pairsIndexList = dataOut.pairsIndexList
299 else:
290 else:
300 pairsIndexList = []
291 pairsIndexList = []
301 for pair in pairsList:
292 for pair in pairsList:
302 if pair not in dataOut.pairsList:
293 if pair not in dataOut.pairsList:
303 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
294 raise ValueError, "Pair %s is not in dataOut.pairsList" %str(pair)
304 pairsIndexList.append(dataOut.pairsList.index(pair))
295 pairsIndexList.append(dataOut.pairsList.index(pair))
305
296
306 if pairsIndexList == []:
297 if pairsIndexList == []:
307 return
298 return
308
299
309 if len(pairsIndexList) > 4:
300 if len(pairsIndexList) > 4:
310 pairsIndexList = pairsIndexList[0:4]
301 pairsIndexList = pairsIndexList[0:4]
311 factor = dataOut.normFactor
302 factor = dataOut.normFactor
312 x = dataOut.getVelRange(1)
303 x = dataOut.getVelRange(1)
313 y = dataOut.getHeiRange()
304 y = dataOut.getHeiRange()
314 z = dataOut.data_spc[:,:,:]/factor
305 z = dataOut.data_spc[:,:,:]/factor
315 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
306 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
316
307
317 noise = dataOut.noise/factor
308 noise = dataOut.noise/factor
318
309
319 zdB = 10*numpy.log10(z)
310 zdB = 10*numpy.log10(z)
320 noisedB = 10*numpy.log10(noise)
311 noisedB = 10*numpy.log10(noise)
321
312
322
313
323 #thisDatetime = dataOut.datatime
314 #thisDatetime = dataOut.datatime
324 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
315 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
325 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
316 title = wintitle + " Cross-Spectra: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
326 xlabel = "Velocity (m/s)"
317 xlabel = "Velocity (m/s)"
327 ylabel = "Range (Km)"
318 ylabel = "Range (Km)"
328
319
329 if not self.isConfig:
320 if not self.isConfig:
330
321
331 nplots = len(pairsIndexList)
322 nplots = len(pairsIndexList)
332
323
333 self.setup(id=id,
324 self.setup(id=id,
334 nplots=nplots,
325 nplots=nplots,
335 wintitle=wintitle,
326 wintitle=wintitle,
336 showprofile=False,
327 showprofile=False,
337 show=show)
328 show=show)
338
329
339 avg = numpy.abs(numpy.average(z, axis=1))
330 avg = numpy.abs(numpy.average(z, axis=1))
340 avgdB = 10*numpy.log10(avg)
331 avgdB = 10*numpy.log10(avg)
341
332
342 if xmin == None: xmin = numpy.nanmin(x)
333 if xmin == None: xmin = numpy.nanmin(x)
343 if xmax == None: xmax = numpy.nanmax(x)
334 if xmax == None: xmax = numpy.nanmax(x)
344 if ymin == None: ymin = numpy.nanmin(y)
335 if ymin == None: ymin = numpy.nanmin(y)
345 if ymax == None: ymax = numpy.nanmax(y)
336 if ymax == None: ymax = numpy.nanmax(y)
346 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
337 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
347 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
338 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
348
339
349 self.FTP_WEI = ftp_wei
340 self.FTP_WEI = ftp_wei
350 self.EXP_CODE = exp_code
341 self.EXP_CODE = exp_code
351 self.SUB_EXP_CODE = sub_exp_code
342 self.SUB_EXP_CODE = sub_exp_code
352 self.PLOT_POS = plot_pos
343 self.PLOT_POS = plot_pos
353
344
354 self.isConfig = True
345 self.isConfig = True
355
346
356 self.setWinTitle(title)
347 self.setWinTitle(title)
357
348
358 for i in range(self.nplots):
349 for i in range(self.nplots):
359 pair = dataOut.pairsList[pairsIndexList[i]]
350 pair = dataOut.pairsList[pairsIndexList[i]]
360 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
351 str_datetime = '%s %s'%(thisDatetime.strftime("%Y/%m/%d"),thisDatetime.strftime("%H:%M:%S"))
361 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[pair[0]], str_datetime)
352 title = "Ch%d: %4.2fdB: %s" %(pair[0], noisedB[pair[0]], str_datetime)
362 zdB = 10.*numpy.log10(dataOut.data_spc[pair[0],:,:]/factor)
353 zdB = 10.*numpy.log10(dataOut.data_spc[pair[0],:,:]/factor)
363 axes0 = self.axesList[i*self.__nsubplots]
354 axes0 = self.axesList[i*self.__nsubplots]
364 axes0.pcolor(x, y, zdB,
355 axes0.pcolor(x, y, zdB,
365 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
356 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
366 xlabel=xlabel, ylabel=ylabel, title=title,
357 xlabel=xlabel, ylabel=ylabel, title=title,
367 ticksize=9, colormap=power_cmap, cblabel='')
358 ticksize=9, colormap=power_cmap, cblabel='')
368
359
369 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[pair[1]], str_datetime)
360 title = "Ch%d: %4.2fdB: %s" %(pair[1], noisedB[pair[1]], str_datetime)
370 zdB = 10.*numpy.log10(dataOut.data_spc[pair[1],:,:]/factor)
361 zdB = 10.*numpy.log10(dataOut.data_spc[pair[1],:,:]/factor)
371 axes0 = self.axesList[i*self.__nsubplots+1]
362 axes0 = self.axesList[i*self.__nsubplots+1]
372 axes0.pcolor(x, y, zdB,
363 axes0.pcolor(x, y, zdB,
373 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
364 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
374 xlabel=xlabel, ylabel=ylabel, title=title,
365 xlabel=xlabel, ylabel=ylabel, title=title,
375 ticksize=9, colormap=power_cmap, cblabel='')
366 ticksize=9, colormap=power_cmap, cblabel='')
376
367
377 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[pair[0],:,:]*dataOut.data_spc[pair[1],:,:])
368 coherenceComplex = dataOut.data_cspc[pairsIndexList[i],:,:]/numpy.sqrt(dataOut.data_spc[pair[0],:,:]*dataOut.data_spc[pair[1],:,:])
378 coherence = numpy.abs(coherenceComplex)
369 coherence = numpy.abs(coherenceComplex)
379 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
370 # phase = numpy.arctan(-1*coherenceComplex.imag/coherenceComplex.real)*180/numpy.pi
380 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
371 phase = numpy.arctan2(coherenceComplex.imag, coherenceComplex.real)*180/numpy.pi
381
372
382 title = "Coherence %d%d" %(pair[0], pair[1])
373 title = "Coherence %d%d" %(pair[0], pair[1])
383 axes0 = self.axesList[i*self.__nsubplots+2]
374 axes0 = self.axesList[i*self.__nsubplots+2]
384 axes0.pcolor(x, y, coherence,
375 axes0.pcolor(x, y, coherence,
385 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=0, zmax=1,
376 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=0, zmax=1,
386 xlabel=xlabel, ylabel=ylabel, title=title,
377 xlabel=xlabel, ylabel=ylabel, title=title,
387 ticksize=9, colormap=coherence_cmap, cblabel='')
378 ticksize=9, colormap=coherence_cmap, cblabel='')
388
379
389 title = "Phase %d%d" %(pair[0], pair[1])
380 title = "Phase %d%d" %(pair[0], pair[1])
390 axes0 = self.axesList[i*self.__nsubplots+3]
381 axes0 = self.axesList[i*self.__nsubplots+3]
391 axes0.pcolor(x, y, phase,
382 axes0.pcolor(x, y, phase,
392 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
383 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
393 xlabel=xlabel, ylabel=ylabel, title=title,
384 xlabel=xlabel, ylabel=ylabel, title=title,
394 ticksize=9, colormap=phase_cmap, cblabel='')
385 ticksize=9, colormap=phase_cmap, cblabel='')
395
386
396
387
397
388
398 self.draw()
389 self.draw()
399
390
400 if save != '':
391 self.save(figpath=figpath,
401
392 figfile=figfile,
402 if figfile == None:
393 save=save,
403 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
394 ftp=ftp,
404 figfile = self.getFilename(name = str_datetime)
395 wr_period=wr_period,
405
396 thisDatetime=thisDatetime)
406 self.counter_imagwr += 1
407
408 if (self.counter_imagwr>=wr_period):
409 # store png plot to local folder
410 self.saveFigure(figpath, figfile)
411 self.counter_imagwr = 0
412
413 if ftp:
414 # store png plot to FTP server according to RT-Web format
415 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
416 ftp_filename = os.path.join(figpath, name)
417 self.saveFigure(figpath, ftp_filename)
418
397
419
398
420 class RTIPlot(Figure):
399 class RTIPlot(Figure):
421
400
422 __isConfig = None
401 __isConfig = None
423 __nsubplots = None
402 __nsubplots = None
424
403
425 WIDTHPROF = None
404 WIDTHPROF = None
426 HEIGHTPROF = None
405 HEIGHTPROF = None
427 PREFIX = 'rti'
406 PREFIX = 'rti'
428
407
429 def __init__(self):
408 def __init__(self):
430
409
431 self.timerange = 2*60*60
410 self.timerange = 2*60*60
432 self.__isConfig = False
411 self.__isConfig = False
433 self.__nsubplots = 1
412 self.__nsubplots = 1
434
413
435 self.WIDTH = 800
414 self.WIDTH = 800
436 self.HEIGHT = 150
415 self.HEIGHT = 150
437 self.WIDTHPROF = 120
416 self.WIDTHPROF = 120
438 self.HEIGHTPROF = 0
417 self.HEIGHTPROF = 0
439 self.counter_imagwr = 0
418 self.counter_imagwr = 0
440
419
441 self.PLOT_CODE = 0
420 self.PLOT_CODE = RTI_CODE
421
442 self.FTP_WEI = None
422 self.FTP_WEI = None
443 self.EXP_CODE = None
423 self.EXP_CODE = None
444 self.SUB_EXP_CODE = None
424 self.SUB_EXP_CODE = None
445 self.PLOT_POS = None
425 self.PLOT_POS = None
446 self.tmin = None
426 self.tmin = None
447 self.tmax = None
427 self.tmax = None
448
428
449 self.xmin = None
429 self.xmin = None
450 self.xmax = None
430 self.xmax = None
451
431
452 self.figfile = None
432 self.figfile = None
453
433
454 def getSubplots(self):
434 def getSubplots(self):
455
435
456 ncol = 1
436 ncol = 1
457 nrow = self.nplots
437 nrow = self.nplots
458
438
459 return nrow, ncol
439 return nrow, ncol
460
440
461 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
441 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
462
442
463 self.__showprofile = showprofile
443 self.__showprofile = showprofile
464 self.nplots = nplots
444 self.nplots = nplots
465
445
466 ncolspan = 1
446 ncolspan = 1
467 colspan = 1
447 colspan = 1
468 if showprofile:
448 if showprofile:
469 ncolspan = 7
449 ncolspan = 7
470 colspan = 6
450 colspan = 6
471 self.__nsubplots = 2
451 self.__nsubplots = 2
472
452
473 self.createFigure(id = id,
453 self.createFigure(id = id,
474 wintitle = wintitle,
454 wintitle = wintitle,
475 widthplot = self.WIDTH + self.WIDTHPROF,
455 widthplot = self.WIDTH + self.WIDTHPROF,
476 heightplot = self.HEIGHT + self.HEIGHTPROF,
456 heightplot = self.HEIGHT + self.HEIGHTPROF,
477 show=show)
457 show=show)
478
458
479 nrow, ncol = self.getSubplots()
459 nrow, ncol = self.getSubplots()
480
460
481 counter = 0
461 counter = 0
482 for y in range(nrow):
462 for y in range(nrow):
483 for x in range(ncol):
463 for x in range(ncol):
484
464
485 if counter >= self.nplots:
465 if counter >= self.nplots:
486 break
466 break
487
467
488 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
468 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
489
469
490 if showprofile:
470 if showprofile:
491 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
471 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
492
472
493 counter += 1
473 counter += 1
494
474
495 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
475 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
496 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
476 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
497 timerange=None,
477 timerange=None,
498 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
478 save=False, figpath='./', lastone=0,figfile=None, ftp=False, wr_period=1, show=True,
499 server=None, folder=None, username=None, password=None,
479 server=None, folder=None, username=None, password=None,
500 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
480 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
501
481
502 """
482 """
503
483
504 Input:
484 Input:
505 dataOut :
485 dataOut :
506 id :
486 id :
507 wintitle :
487 wintitle :
508 channelList :
488 channelList :
509 showProfile :
489 showProfile :
510 xmin : None,
490 xmin : None,
511 xmax : None,
491 xmax : None,
512 ymin : None,
492 ymin : None,
513 ymax : None,
493 ymax : None,
514 zmin : None,
494 zmin : None,
515 zmax : None
495 zmax : None
516 """
496 """
517
497
518 if channelList == None:
498 if channelList == None:
519 channelIndexList = dataOut.channelIndexList
499 channelIndexList = dataOut.channelIndexList
520 else:
500 else:
521 channelIndexList = []
501 channelIndexList = []
522 for channel in channelList:
502 for channel in channelList:
523 if channel not in dataOut.channelList:
503 if channel not in dataOut.channelList:
524 raise ValueError, "Channel %d is not in dataOut.channelList"
504 raise ValueError, "Channel %d is not in dataOut.channelList"
525 channelIndexList.append(dataOut.channelList.index(channel))
505 channelIndexList.append(dataOut.channelList.index(channel))
526
506
527 # if timerange != None:
507 # if timerange != None:
528 # self.timerange = timerange
508 # self.timerange = timerange
529
509
530 #tmin = None
510 #tmin = None
531 #tmax = None
511 #tmax = None
532 factor = dataOut.normFactor
512 factor = dataOut.normFactor
533 x = dataOut.getTimeRange()
513 x = dataOut.getTimeRange()
534 y = dataOut.getHeiRange()
514 y = dataOut.getHeiRange()
535
515
536 z = dataOut.data_spc[channelIndexList,:,:]/factor
516 z = dataOut.data_spc[channelIndexList,:,:]/factor
537 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
517 z = numpy.where(numpy.isfinite(z), z, numpy.NAN)
538 avg = numpy.average(z, axis=1)
518 avg = numpy.average(z, axis=1)
539
519
540 avgdB = 10.*numpy.log10(avg)
520 avgdB = 10.*numpy.log10(avg)
541
521
542
522
543 # thisDatetime = dataOut.datatime
523 # thisDatetime = dataOut.datatime
544 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
524 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
545 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
525 title = wintitle + " RTI" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
546 xlabel = ""
526 xlabel = ""
547 ylabel = "Range (Km)"
527 ylabel = "Range (Km)"
548
528
549 if not self.__isConfig:
529 if not self.__isConfig:
550
530
551 nplots = len(channelIndexList)
531 nplots = len(channelIndexList)
552
532
553 self.setup(id=id,
533 self.setup(id=id,
554 nplots=nplots,
534 nplots=nplots,
555 wintitle=wintitle,
535 wintitle=wintitle,
556 showprofile=showprofile,
536 showprofile=showprofile,
557 show=show)
537 show=show)
558
538
559 if timerange != None:
539 if timerange != None:
560 self.timerange = timerange
540 self.timerange = timerange
561
541
562 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
542 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
563
543
564 noise = dataOut.noise/factor
544 noise = dataOut.noise/factor
565 noisedB = 10*numpy.log10(noise)
545 noisedB = 10*numpy.log10(noise)
566
546
567 if ymin == None: ymin = numpy.nanmin(y)
547 if ymin == None: ymin = numpy.nanmin(y)
568 if ymax == None: ymax = numpy.nanmax(y)
548 if ymax == None: ymax = numpy.nanmax(y)
569 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
549 if zmin == None: zmin = numpy.floor(numpy.nanmin(noisedB)) - 3
570 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
550 if zmax == None: zmax = numpy.ceil(numpy.nanmax(avgdB)) + 3
571
551
572 self.FTP_WEI = ftp_wei
552 self.FTP_WEI = ftp_wei
573 self.EXP_CODE = exp_code
553 self.EXP_CODE = exp_code
574 self.SUB_EXP_CODE = sub_exp_code
554 self.SUB_EXP_CODE = sub_exp_code
575 self.PLOT_POS = plot_pos
555 self.PLOT_POS = plot_pos
576
556
577 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
557 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
578 self.__isConfig = True
558 self.__isConfig = True
579 self.figfile = figfile
559 self.figfile = figfile
580
560
581 self.setWinTitle(title)
561 self.setWinTitle(title)
582
562
583 if ((self.xmax - x[1]) < (x[1]-x[0])):
563 if ((self.xmax - x[1]) < (x[1]-x[0])):
584 x[1] = self.xmax
564 x[1] = self.xmax
585
565
586 for i in range(self.nplots):
566 for i in range(self.nplots):
587 title = "Channel %d: %s" %(dataOut.channelList[i]+1, thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
567 title = "Channel %d: %s" %(dataOut.channelList[i]+1, thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
588 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
568 if ((dataOut.azimuth!=None) and (dataOut.zenith!=None)):
589 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
569 title = title + '_' + 'azimuth,zenith=%2.2f,%2.2f'%(dataOut.azimuth, dataOut.zenith)
590 axes = self.axesList[i*self.__nsubplots]
570 axes = self.axesList[i*self.__nsubplots]
591 zdB = avgdB[i].reshape((1,-1))
571 zdB = avgdB[i].reshape((1,-1))
592 axes.pcolorbuffer(x, y, zdB,
572 axes.pcolorbuffer(x, y, zdB,
593 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
573 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
594 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
574 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
595 ticksize=9, cblabel='', cbsize="1%")
575 ticksize=9, cblabel='', cbsize="1%")
596
576
597 if self.__showprofile:
577 if self.__showprofile:
598 axes = self.axesList[i*self.__nsubplots +1]
578 axes = self.axesList[i*self.__nsubplots +1]
599 axes.pline(avgdB[i], y,
579 axes.pline(avgdB[i], y,
600 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
580 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
601 xlabel='dB', ylabel='', title='',
581 xlabel='dB', ylabel='', title='',
602 ytick_visible=False,
582 ytick_visible=False,
603 grid='x')
583 grid='x')
604
584
605 self.draw()
585 self.draw()
606
607 if save:
608
586
609 if self.figfile == None:
610 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
611 self.figfile = self.getFilename(name = str_datetime)
612
613 self.counter_imagwr += 1
614
615 if (self.counter_imagwr>=wr_period):
616 # store png plot to local folder
617 self.saveFigure(figpath, self.figfile)
618 self.counter_imagwr = 0
619
620 if ftp:
621 # store png plot to FTP server according to RT-Web format
622 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
623 ftp_filename = os.path.join(figpath, name)
624 self.saveFigure(figpath, ftp_filename)
625
626 if x[1] >= self.axesList[0].xmax:
587 if x[1] >= self.axesList[0].xmax:
627 self.counter_imagwr = wr_period
588 self.counter_imagwr = wr_period
628 self.__isConfig = False
589 self.__isConfig = False
629 self.figfile = None
590 self.figfile = None
591
592 self.save(figpath=figpath,
593 figfile=figfile,
594 save=save,
595 ftp=ftp,
596 wr_period=wr_period,
597 thisDatetime=thisDatetime,
598 update_figfile=False)
630
599
631 class CoherenceMap(Figure):
600 class CoherenceMap(Figure):
632 isConfig = None
601 isConfig = None
633 __nsubplots = None
602 __nsubplots = None
634
603
635 WIDTHPROF = None
604 WIDTHPROF = None
636 HEIGHTPROF = None
605 HEIGHTPROF = None
637 PREFIX = 'cmap'
606 PREFIX = 'cmap'
638
607
639 def __init__(self):
608 def __init__(self):
640 self.timerange = 2*60*60
609 self.timerange = 2*60*60
641 self.isConfig = False
610 self.isConfig = False
642 self.__nsubplots = 1
611 self.__nsubplots = 1
643
612
644 self.WIDTH = 800
613 self.WIDTH = 800
645 self.HEIGHT = 150
614 self.HEIGHT = 150
646 self.WIDTHPROF = 120
615 self.WIDTHPROF = 120
647 self.HEIGHTPROF = 0
616 self.HEIGHTPROF = 0
648 self.counter_imagwr = 0
617 self.counter_imagwr = 0
649
618
650 self.PLOT_CODE = 3
619 self.PLOT_CODE = COH_CODE
620
651 self.FTP_WEI = None
621 self.FTP_WEI = None
652 self.EXP_CODE = None
622 self.EXP_CODE = None
653 self.SUB_EXP_CODE = None
623 self.SUB_EXP_CODE = None
654 self.PLOT_POS = None
624 self.PLOT_POS = None
655 self.counter_imagwr = 0
625 self.counter_imagwr = 0
656
626
657 self.xmin = None
627 self.xmin = None
658 self.xmax = None
628 self.xmax = None
659
629
660 def getSubplots(self):
630 def getSubplots(self):
661 ncol = 1
631 ncol = 1
662 nrow = self.nplots*2
632 nrow = self.nplots*2
663
633
664 return nrow, ncol
634 return nrow, ncol
665
635
666 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
636 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
667 self.__showprofile = showprofile
637 self.__showprofile = showprofile
668 self.nplots = nplots
638 self.nplots = nplots
669
639
670 ncolspan = 1
640 ncolspan = 1
671 colspan = 1
641 colspan = 1
672 if showprofile:
642 if showprofile:
673 ncolspan = 7
643 ncolspan = 7
674 colspan = 6
644 colspan = 6
675 self.__nsubplots = 2
645 self.__nsubplots = 2
676
646
677 self.createFigure(id = id,
647 self.createFigure(id = id,
678 wintitle = wintitle,
648 wintitle = wintitle,
679 widthplot = self.WIDTH + self.WIDTHPROF,
649 widthplot = self.WIDTH + self.WIDTHPROF,
680 heightplot = self.HEIGHT + self.HEIGHTPROF,
650 heightplot = self.HEIGHT + self.HEIGHTPROF,
681 show=True)
651 show=True)
682
652
683 nrow, ncol = self.getSubplots()
653 nrow, ncol = self.getSubplots()
684
654
685 for y in range(nrow):
655 for y in range(nrow):
686 for x in range(ncol):
656 for x in range(ncol):
687
657
688 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
658 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
689
659
690 if showprofile:
660 if showprofile:
691 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
661 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan+colspan, 1, 1)
692
662
693 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
663 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
694 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
664 xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None,
695 timerange=None,
665 timerange=None,
696 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
666 save=False, figpath='./', figfile=None, ftp=False, wr_period=1,
697 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
667 coherence_cmap='jet', phase_cmap='RdBu_r', show=True,
698 server=None, folder=None, username=None, password=None,
668 server=None, folder=None, username=None, password=None,
699 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
669 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
700
670
701 if pairsList == None:
671 if pairsList == None:
702 pairsIndexList = dataOut.pairsIndexList
672 pairsIndexList = dataOut.pairsIndexList
703 else:
673 else:
704 pairsIndexList = []
674 pairsIndexList = []
705 for pair in pairsList:
675 for pair in pairsList:
706 if pair not in dataOut.pairsList:
676 if pair not in dataOut.pairsList:
707 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
677 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
708 pairsIndexList.append(dataOut.pairsList.index(pair))
678 pairsIndexList.append(dataOut.pairsList.index(pair))
709
679
710 if pairsIndexList == []:
680 if pairsIndexList == []:
711 return
681 return
712
682
713 if len(pairsIndexList) > 4:
683 if len(pairsIndexList) > 4:
714 pairsIndexList = pairsIndexList[0:4]
684 pairsIndexList = pairsIndexList[0:4]
715
685
716 # tmin = None
686 # tmin = None
717 # tmax = None
687 # tmax = None
718 x = dataOut.getTimeRange()
688 x = dataOut.getTimeRange()
719 y = dataOut.getHeiRange()
689 y = dataOut.getHeiRange()
720
690
721 #thisDatetime = dataOut.datatime
691 #thisDatetime = dataOut.datatime
722 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
692 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
723 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
693 title = wintitle + " CoherenceMap" #: %s" %(thisDatetime.strftime("%d-%b-%Y"))
724 xlabel = ""
694 xlabel = ""
725 ylabel = "Range (Km)"
695 ylabel = "Range (Km)"
726
696
727 if not self.isConfig:
697 if not self.isConfig:
728 nplots = len(pairsIndexList)
698 nplots = len(pairsIndexList)
729 self.setup(id=id,
699 self.setup(id=id,
730 nplots=nplots,
700 nplots=nplots,
731 wintitle=wintitle,
701 wintitle=wintitle,
732 showprofile=showprofile,
702 showprofile=showprofile,
733 show=show)
703 show=show)
734
704
735 if timerange != None:
705 if timerange != None:
736 self.timerange = timerange
706 self.timerange = timerange
737
707
738 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
708 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
739
709
740 if ymin == None: ymin = numpy.nanmin(y)
710 if ymin == None: ymin = numpy.nanmin(y)
741 if ymax == None: ymax = numpy.nanmax(y)
711 if ymax == None: ymax = numpy.nanmax(y)
742 if zmin == None: zmin = 0.
712 if zmin == None: zmin = 0.
743 if zmax == None: zmax = 1.
713 if zmax == None: zmax = 1.
744
714
745 self.FTP_WEI = ftp_wei
715 self.FTP_WEI = ftp_wei
746 self.EXP_CODE = exp_code
716 self.EXP_CODE = exp_code
747 self.SUB_EXP_CODE = sub_exp_code
717 self.SUB_EXP_CODE = sub_exp_code
748 self.PLOT_POS = plot_pos
718 self.PLOT_POS = plot_pos
749
719
750 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
720 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
751
721
752 self.isConfig = True
722 self.isConfig = True
753
723
754 self.setWinTitle(title)
724 self.setWinTitle(title)
755
725
756 if ((self.xmax - x[1]) < (x[1]-x[0])):
726 if ((self.xmax - x[1]) < (x[1]-x[0])):
757 x[1] = self.xmax
727 x[1] = self.xmax
758
728
759 for i in range(self.nplots):
729 for i in range(self.nplots):
760
730
761 pair = dataOut.pairsList[pairsIndexList[i]]
731 pair = dataOut.pairsList[pairsIndexList[i]]
762
732
763 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
733 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
764 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
734 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
765 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
735 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
766
736
767
737
768 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
738 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
769 coherence = numpy.abs(avgcoherenceComplex)
739 coherence = numpy.abs(avgcoherenceComplex)
770
740
771 z = coherence.reshape((1,-1))
741 z = coherence.reshape((1,-1))
772
742
773 counter = 0
743 counter = 0
774
744
775 title = "Coherence %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
745 title = "Coherence %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
776 axes = self.axesList[i*self.__nsubplots*2]
746 axes = self.axesList[i*self.__nsubplots*2]
777 axes.pcolorbuffer(x, y, z,
747 axes.pcolorbuffer(x, y, z,
778 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
748 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=zmin, zmax=zmax,
779 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
749 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
780 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
750 ticksize=9, cblabel='', colormap=coherence_cmap, cbsize="1%")
781
751
782 if self.__showprofile:
752 if self.__showprofile:
783 counter += 1
753 counter += 1
784 axes = self.axesList[i*self.__nsubplots*2 + counter]
754 axes = self.axesList[i*self.__nsubplots*2 + counter]
785 axes.pline(coherence, y,
755 axes.pline(coherence, y,
786 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
756 xmin=zmin, xmax=zmax, ymin=ymin, ymax=ymax,
787 xlabel='', ylabel='', title='', ticksize=7,
757 xlabel='', ylabel='', title='', ticksize=7,
788 ytick_visible=False, nxticks=5,
758 ytick_visible=False, nxticks=5,
789 grid='x')
759 grid='x')
790
760
791 counter += 1
761 counter += 1
792
762
793 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
763 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
794
764
795 z = phase.reshape((1,-1))
765 z = phase.reshape((1,-1))
796
766
797 title = "Phase %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
767 title = "Phase %d%d: %s" %(pair[0], pair[1], thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
798 axes = self.axesList[i*self.__nsubplots*2 + counter]
768 axes = self.axesList[i*self.__nsubplots*2 + counter]
799 axes.pcolorbuffer(x, y, z,
769 axes.pcolorbuffer(x, y, z,
800 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
770 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax, zmin=-180, zmax=180,
801 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
771 xlabel=xlabel, ylabel=ylabel, title=title, rti=True, XAxisAsTime=True,
802 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
772 ticksize=9, cblabel='', colormap=phase_cmap, cbsize="1%")
803
773
804 if self.__showprofile:
774 if self.__showprofile:
805 counter += 1
775 counter += 1
806 axes = self.axesList[i*self.__nsubplots*2 + counter]
776 axes = self.axesList[i*self.__nsubplots*2 + counter]
807 axes.pline(phase, y,
777 axes.pline(phase, y,
808 xmin=-180, xmax=180, ymin=ymin, ymax=ymax,
778 xmin=-180, xmax=180, ymin=ymin, ymax=ymax,
809 xlabel='', ylabel='', title='', ticksize=7,
779 xlabel='', ylabel='', title='', ticksize=7,
810 ytick_visible=False, nxticks=4,
780 ytick_visible=False, nxticks=4,
811 grid='x')
781 grid='x')
812
782
813 self.draw()
783 self.draw()
814
784
815 if x[1] >= self.axesList[0].xmax:
785 if x[1] >= self.axesList[0].xmax:
816 self.counter_imagwr = wr_period
786 self.counter_imagwr = wr_period
817 self.__isConfig = False
787 self.__isConfig = False
818
788 self.figfile = None
819 if save:
820
821 if figfile == None:
822 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
823 figfile = self.getFilename(name = str_datetime)
824
825 self.counter_imagwr += 1
826
789
827 if (self.counter_imagwr>=wr_period):
790 self.save(figpath=figpath,
828 # store png plot to local folder
791 figfile=figfile,
829 self.saveFigure(figpath, figfile)
792 save=save,
830 self.counter_imagwr = 0
793 ftp=ftp,
831
794 wr_period=wr_period,
832 if ftp:
795 thisDatetime=thisDatetime,
833 # store png plot to FTP server according to RT-Web format
796 update_figfile=False)
834 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
835 ftp_filename = os.path.join(figpath, name)
836 self.saveFigure(figpath, ftp_filename)
837
797
838 class PowerProfile(Figure):
798 class PowerProfile(Figure):
799
839 isConfig = None
800 isConfig = None
840 __nsubplots = None
801 __nsubplots = None
841
802
842 WIDTHPROF = None
803 WIDTHPROF = None
843 HEIGHTPROF = None
804 HEIGHTPROF = None
844 PREFIX = 'spcprofile'
805 PREFIX = 'spcprofile'
845
806
846 def __init__(self):
807 def __init__(self):
847 self.isConfig = False
808 self.isConfig = False
848 self.__nsubplots = 1
809 self.__nsubplots = 1
849
810
811 self.PLOT_CODE = POWER_CODE
812
850 self.WIDTH = 300
813 self.WIDTH = 300
851 self.HEIGHT = 500
814 self.HEIGHT = 500
852 self.counter_imagwr = 0
815 self.counter_imagwr = 0
853
816
854 def getSubplots(self):
817 def getSubplots(self):
855 ncol = 1
818 ncol = 1
856 nrow = 1
819 nrow = 1
857
820
858 return nrow, ncol
821 return nrow, ncol
859
822
860 def setup(self, id, nplots, wintitle, show):
823 def setup(self, id, nplots, wintitle, show):
861
824
862 self.nplots = nplots
825 self.nplots = nplots
863
826
864 ncolspan = 1
827 ncolspan = 1
865 colspan = 1
828 colspan = 1
866
829
867 self.createFigure(id = id,
830 self.createFigure(id = id,
868 wintitle = wintitle,
831 wintitle = wintitle,
869 widthplot = self.WIDTH,
832 widthplot = self.WIDTH,
870 heightplot = self.HEIGHT,
833 heightplot = self.HEIGHT,
871 show=show)
834 show=show)
872
835
873 nrow, ncol = self.getSubplots()
836 nrow, ncol = self.getSubplots()
874
837
875 counter = 0
838 counter = 0
876 for y in range(nrow):
839 for y in range(nrow):
877 for x in range(ncol):
840 for x in range(ncol):
878 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
841 self.addAxes(nrow, ncol*ncolspan, y, x*ncolspan, colspan, 1)
879
842
880 def run(self, dataOut, id, wintitle="", channelList=None,
843 def run(self, dataOut, id, wintitle="", channelList=None,
881 xmin=None, xmax=None, ymin=None, ymax=None,
844 xmin=None, xmax=None, ymin=None, ymax=None,
882 save=False, figpath='./', figfile=None, show=True,
845 save=False, figpath='./', figfile=None, show=True,
883 ftp=False, wr_period=1, server=None,
846 ftp=False, wr_period=1, server=None,
884 folder=None, username=None, password=None):
847 folder=None, username=None, password=None):
885
848
886
849
887 if channelList == None:
850 if channelList == None:
888 channelIndexList = dataOut.channelIndexList
851 channelIndexList = dataOut.channelIndexList
889 channelList = dataOut.channelList
852 channelList = dataOut.channelList
890 else:
853 else:
891 channelIndexList = []
854 channelIndexList = []
892 for channel in channelList:
855 for channel in channelList:
893 if channel not in dataOut.channelList:
856 if channel not in dataOut.channelList:
894 raise ValueError, "Channel %d is not in dataOut.channelList"
857 raise ValueError, "Channel %d is not in dataOut.channelList"
895 channelIndexList.append(dataOut.channelList.index(channel))
858 channelIndexList.append(dataOut.channelList.index(channel))
896
859
897 factor = dataOut.normFactor
860 factor = dataOut.normFactor
898
861
899 y = dataOut.getHeiRange()
862 y = dataOut.getHeiRange()
900
863
901 #for voltage
864 #for voltage
902 if dataOut.type == 'Voltage':
865 if dataOut.type == 'Voltage':
903 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
866 x = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
904 x = x.real
867 x = x.real
905 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
868 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
906
869
907 #for spectra
870 #for spectra
908 if dataOut.type == 'Spectra':
871 if dataOut.type == 'Spectra':
909 x = dataOut.data_spc[channelIndexList,:,:]/factor
872 x = dataOut.data_spc[channelIndexList,:,:]/factor
910 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
873 x = numpy.where(numpy.isfinite(x), x, numpy.NAN)
911 x = numpy.average(x, axis=1)
874 x = numpy.average(x, axis=1)
912
875
913
876
914 xdB = 10*numpy.log10(x)
877 xdB = 10*numpy.log10(x)
915
878
916 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
879 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
917 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
880 title = wintitle + " Power Profile %s" %(thisDatetime.strftime("%d-%b-%Y"))
918 xlabel = "dB"
881 xlabel = "dB"
919 ylabel = "Range (Km)"
882 ylabel = "Range (Km)"
920
883
921 if not self.isConfig:
884 if not self.isConfig:
922
885
923 nplots = 1
886 nplots = 1
924
887
925 self.setup(id=id,
888 self.setup(id=id,
926 nplots=nplots,
889 nplots=nplots,
927 wintitle=wintitle,
890 wintitle=wintitle,
928 show=show)
891 show=show)
929
892
930 if ymin == None: ymin = numpy.nanmin(y)
893 if ymin == None: ymin = numpy.nanmin(y)
931 if ymax == None: ymax = numpy.nanmax(y)
894 if ymax == None: ymax = numpy.nanmax(y)
932 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
895 if xmin == None: xmin = numpy.nanmin(xdB)*0.9
933 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
896 if xmax == None: xmax = numpy.nanmax(xdB)*1.1
934
897
935 self.__isConfig = True
898 self.__isConfig = True
936
899
937 self.setWinTitle(title)
900 self.setWinTitle(title)
938
901
939 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
902 title = "Power Profile: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
940 axes = self.axesList[0]
903 axes = self.axesList[0]
941
904
942 legendlabels = ["channel %d"%x for x in channelList]
905 legendlabels = ["channel %d"%x for x in channelList]
943 axes.pmultiline(xdB, y,
906 axes.pmultiline(xdB, y,
944 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
907 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
945 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
908 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels,
946 ytick_visible=True, nxticks=5,
909 ytick_visible=True, nxticks=5,
947 grid='x')
910 grid='x')
948
911
949 self.draw()
912 self.draw()
950
913
951 if save:
914 self.save(figpath=figpath,
952
915 figfile=figfile,
953 if figfile == None:
916 save=save,
954 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
917 ftp=ftp,
955 figfile = self.getFilename(name = str_datetime)
918 wr_period=wr_period,
956
919 thisDatetime=thisDatetime)
957 self.counter_imagwr += 1
958
959 if (self.counter_imagwr>=wr_period):
960 # store png plot to local folder
961 self.saveFigure(figpath, figfile)
962 self.counter_imagwr = 0
963
920
964 class Noise(Figure):
921 class Noise(Figure):
965
922
966 isConfig = None
923 isConfig = None
967 __nsubplots = None
924 __nsubplots = None
968
925
969 PREFIX = 'noise'
926 PREFIX = 'noise'
970
927
971 def __init__(self):
928 def __init__(self):
972
929
973 self.timerange = 24*60*60
930 self.timerange = 24*60*60
974 self.isConfig = False
931 self.isConfig = False
975 self.__nsubplots = 1
932 self.__nsubplots = 1
976 self.counter_imagwr = 0
933 self.counter_imagwr = 0
977 self.WIDTH = 600
934 self.WIDTH = 600
978 self.HEIGHT = 300
935 self.HEIGHT = 300
979 self.WIDTHPROF = 120
936 self.WIDTHPROF = 120
980 self.HEIGHTPROF = 0
937 self.HEIGHTPROF = 0
981 self.xdata = None
938 self.xdata = None
982 self.ydata = None
939 self.ydata = None
983
940
984 self.PLOT_CODE = 17
941 self.PLOT_CODE = NOISE_CODE
942
985 self.FTP_WEI = None
943 self.FTP_WEI = None
986 self.EXP_CODE = None
944 self.EXP_CODE = None
987 self.SUB_EXP_CODE = None
945 self.SUB_EXP_CODE = None
988 self.PLOT_POS = None
946 self.PLOT_POS = None
989 self.figfile = None
947 self.figfile = None
990
948
991 self.xmin = None
949 self.xmin = None
992 self.xmax = None
950 self.xmax = None
993
951
994 def getSubplots(self):
952 def getSubplots(self):
995
953
996 ncol = 1
954 ncol = 1
997 nrow = 1
955 nrow = 1
998
956
999 return nrow, ncol
957 return nrow, ncol
1000
958
1001 def openfile(self, filename):
959 def openfile(self, filename):
1002 f = open(filename,'w+')
960 f = open(filename,'w+')
1003 f.write('\n\n')
961 f.write('\n\n')
1004 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
962 f.write('JICAMARCA RADIO OBSERVATORY - Noise \n')
1005 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
963 f.write('DD MM YYYY HH MM SS Channel0 Channel1 Channel2 Channel3\n\n' )
1006 f.close()
964 f.close()
1007
965
1008 def save_data(self, filename_phase, data, data_datetime):
966 def save_data(self, filename_phase, data, data_datetime):
1009 f=open(filename_phase,'a')
967 f=open(filename_phase,'a')
1010 timetuple_data = data_datetime.timetuple()
968 timetuple_data = data_datetime.timetuple()
1011 day = str(timetuple_data.tm_mday)
969 day = str(timetuple_data.tm_mday)
1012 month = str(timetuple_data.tm_mon)
970 month = str(timetuple_data.tm_mon)
1013 year = str(timetuple_data.tm_year)
971 year = str(timetuple_data.tm_year)
1014 hour = str(timetuple_data.tm_hour)
972 hour = str(timetuple_data.tm_hour)
1015 minute = str(timetuple_data.tm_min)
973 minute = str(timetuple_data.tm_min)
1016 second = str(timetuple_data.tm_sec)
974 second = str(timetuple_data.tm_sec)
1017 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
975 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1018 f.close()
976 f.close()
1019
977
1020
978
1021 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
979 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1022
980
1023 self.__showprofile = showprofile
981 self.__showprofile = showprofile
1024 self.nplots = nplots
982 self.nplots = nplots
1025
983
1026 ncolspan = 7
984 ncolspan = 7
1027 colspan = 6
985 colspan = 6
1028 self.__nsubplots = 2
986 self.__nsubplots = 2
1029
987
1030 self.createFigure(id = id,
988 self.createFigure(id = id,
1031 wintitle = wintitle,
989 wintitle = wintitle,
1032 widthplot = self.WIDTH+self.WIDTHPROF,
990 widthplot = self.WIDTH+self.WIDTHPROF,
1033 heightplot = self.HEIGHT+self.HEIGHTPROF,
991 heightplot = self.HEIGHT+self.HEIGHTPROF,
1034 show=show)
992 show=show)
1035
993
1036 nrow, ncol = self.getSubplots()
994 nrow, ncol = self.getSubplots()
1037
995
1038 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
996 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1039
997
1040
998
1041 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
999 def run(self, dataOut, id, wintitle="", channelList=None, showprofile='True',
1042 xmin=None, xmax=None, ymin=None, ymax=None,
1000 xmin=None, xmax=None, ymin=None, ymax=None,
1043 timerange=None,
1001 timerange=None,
1044 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1002 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1045 server=None, folder=None, username=None, password=None,
1003 server=None, folder=None, username=None, password=None,
1046 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1004 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1047
1005
1048 if channelList == None:
1006 if channelList == None:
1049 channelIndexList = dataOut.channelIndexList
1007 channelIndexList = dataOut.channelIndexList
1050 channelList = dataOut.channelList
1008 channelList = dataOut.channelList
1051 else:
1009 else:
1052 channelIndexList = []
1010 channelIndexList = []
1053 for channel in channelList:
1011 for channel in channelList:
1054 if channel not in dataOut.channelList:
1012 if channel not in dataOut.channelList:
1055 raise ValueError, "Channel %d is not in dataOut.channelList"
1013 raise ValueError, "Channel %d is not in dataOut.channelList"
1056 channelIndexList.append(dataOut.channelList.index(channel))
1014 channelIndexList.append(dataOut.channelList.index(channel))
1057
1015
1058 x = dataOut.getTimeRange()
1016 x = dataOut.getTimeRange()
1059 #y = dataOut.getHeiRange()
1017 #y = dataOut.getHeiRange()
1060 factor = dataOut.normFactor
1018 factor = dataOut.normFactor
1061 noise = dataOut.noise/factor
1019 noise = dataOut.noise/factor
1062 noisedB = 10*numpy.log10(noise)
1020 noisedB = 10*numpy.log10(noise)
1063
1021
1064 #thisDatetime = dataOut.datatime
1022 #thisDatetime = dataOut.datatime
1065 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1023 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1066 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1024 title = wintitle + " Noise" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1067 xlabel = ""
1025 xlabel = ""
1068 ylabel = "Intensity (dB)"
1026 ylabel = "Intensity (dB)"
1069
1027
1070 if not self.isConfig:
1028 if not self.isConfig:
1071
1029
1072 nplots = 1
1030 nplots = 1
1073
1031
1074 self.setup(id=id,
1032 self.setup(id=id,
1075 nplots=nplots,
1033 nplots=nplots,
1076 wintitle=wintitle,
1034 wintitle=wintitle,
1077 showprofile=showprofile,
1035 showprofile=showprofile,
1078 show=show)
1036 show=show)
1079
1037
1080 if timerange != None:
1038 if timerange != None:
1081 self.timerange = timerange
1039 self.timerange = timerange
1082
1040
1083 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1041 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1084
1042
1085 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1043 if ymin == None: ymin = numpy.floor(numpy.nanmin(noisedB)) - 10.0
1086 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1044 if ymax == None: ymax = numpy.nanmax(noisedB) + 10.0
1087
1045
1088 self.FTP_WEI = ftp_wei
1046 self.FTP_WEI = ftp_wei
1089 self.EXP_CODE = exp_code
1047 self.EXP_CODE = exp_code
1090 self.SUB_EXP_CODE = sub_exp_code
1048 self.SUB_EXP_CODE = sub_exp_code
1091 self.PLOT_POS = plot_pos
1049 self.PLOT_POS = plot_pos
1092
1050
1093
1051
1094 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1052 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1095 self.isConfig = True
1053 self.isConfig = True
1096 self.figfile = figfile
1054 self.figfile = figfile
1097 self.xdata = numpy.array([])
1055 self.xdata = numpy.array([])
1098 self.ydata = numpy.array([])
1056 self.ydata = numpy.array([])
1099
1057
1100 #open file beacon phase
1058 #open file beacon phase
1101 path = '%s%03d' %(self.PREFIX, self.id)
1059 path = '%s%03d' %(self.PREFIX, self.id)
1102 noise_file = os.path.join(path,'%s.txt'%self.name)
1060 noise_file = os.path.join(path,'%s.txt'%self.name)
1103 self.filename_noise = os.path.join(figpath,noise_file)
1061 self.filename_noise = os.path.join(figpath,noise_file)
1104 self.openfile(self.filename_noise)
1062 self.openfile(self.filename_noise)
1105
1063
1106
1064
1107 #store data beacon phase
1065 #store data beacon phase
1108 self.save_data(self.filename_noise, noisedB, thisDatetime)
1066 self.save_data(self.filename_noise, noisedB, thisDatetime)
1109
1067
1110
1068
1111 self.setWinTitle(title)
1069 self.setWinTitle(title)
1112
1070
1113
1071
1114 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1072 title = "Noise %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1115
1073
1116 legendlabels = ["channel %d"%(idchannel+1) for idchannel in channelList]
1074 legendlabels = ["channel %d"%(idchannel+1) for idchannel in channelList]
1117 axes = self.axesList[0]
1075 axes = self.axesList[0]
1118
1076
1119 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1077 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1120
1078
1121 if len(self.ydata)==0:
1079 if len(self.ydata)==0:
1122 self.ydata = noisedB[channelIndexList].reshape(-1,1)
1080 self.ydata = noisedB[channelIndexList].reshape(-1,1)
1123 else:
1081 else:
1124 self.ydata = numpy.hstack((self.ydata, noisedB[channelIndexList].reshape(-1,1)))
1082 self.ydata = numpy.hstack((self.ydata, noisedB[channelIndexList].reshape(-1,1)))
1125
1083
1126
1084
1127 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1085 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1128 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1086 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1129 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1087 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1130 XAxisAsTime=True, grid='both'
1088 XAxisAsTime=True, grid='both'
1131 )
1089 )
1132
1090
1133 self.draw()
1091 self.draw()
1134
1092
1135 if x[1] >= self.axesList[0].xmax:
1093 if x[1] >= self.axesList[0].xmax:
1136 self.counter_imagwr = wr_period
1094 self.counter_imagwr = wr_period
1137 del self.xdata
1095 del self.xdata
1138 del self.ydata
1096 del self.ydata
1139 self.__isConfig = False
1097 self.__isConfig = False
1140
1098 self.figfile = None
1141 if save != '':
1142
1143 if self.figfile == None:
1144 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1145 self.figfile = self.getFilename(name = str_datetime)
1146
1147 self.counter_imagwr += 1
1148
1099
1149 if (self.counter_imagwr>=wr_period):
1100 self.save(figpath=figpath,
1150 # store png plot to local folder
1101 figfile=figfile,
1151 self.saveFigure(figpath, self.figfile)
1102 save=save,
1152 self.counter_imagwr = 0
1103 ftp=ftp,
1153
1104 wr_period=wr_period,
1154 if ftp:
1105 thisDatetime=thisDatetime,
1155 # store png plot to FTP server according to RT-Web format
1106 update_figfile=False)
1156 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
1157 ftp_filename = os.path.join(figpath, name)
1158 self.saveFigure(figpath, ftp_filename)
1159
1107
1160
1108
1161 class BeaconPhase(Figure):
1109 class BeaconPhase(Figure):
1162
1110
1163 __isConfig = None
1111 __isConfig = None
1164 __nsubplots = None
1112 __nsubplots = None
1165
1113
1166 PREFIX = 'beacon_phase'
1114 PREFIX = 'beacon_phase'
1167
1115
1168 def __init__(self):
1116 def __init__(self):
1169
1117
1170 self.timerange = 24*60*60
1118 self.timerange = 24*60*60
1171 self.__isConfig = False
1119 self.__isConfig = False
1172 self.__nsubplots = 1
1120 self.__nsubplots = 1
1173 self.counter_imagwr = 0
1121 self.counter_imagwr = 0
1174 self.WIDTH = 600
1122 self.WIDTH = 600
1175 self.HEIGHT = 300
1123 self.HEIGHT = 300
1176 self.WIDTHPROF = 120
1124 self.WIDTHPROF = 120
1177 self.HEIGHTPROF = 0
1125 self.HEIGHTPROF = 0
1178 self.xdata = None
1126 self.xdata = None
1179 self.ydata = None
1127 self.ydata = None
1180
1128
1181 self.PLOT_CODE = 18
1129 self.PLOT_CODE = BEACON_CODE
1130
1182 self.FTP_WEI = None
1131 self.FTP_WEI = None
1183 self.EXP_CODE = None
1132 self.EXP_CODE = None
1184 self.SUB_EXP_CODE = None
1133 self.SUB_EXP_CODE = None
1185 self.PLOT_POS = None
1134 self.PLOT_POS = None
1186
1135
1187 self.filename_phase = None
1136 self.filename_phase = None
1188
1137
1189 self.figfile = None
1138 self.figfile = None
1190
1139
1191 self.xmin = None
1140 self.xmin = None
1192 self.xmax = None
1141 self.xmax = None
1193
1142
1194 def getSubplots(self):
1143 def getSubplots(self):
1195
1144
1196 ncol = 1
1145 ncol = 1
1197 nrow = 1
1146 nrow = 1
1198
1147
1199 return nrow, ncol
1148 return nrow, ncol
1200
1149
1201 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1150 def setup(self, id, nplots, wintitle, showprofile=True, show=True):
1202
1151
1203 self.__showprofile = showprofile
1152 self.__showprofile = showprofile
1204 self.nplots = nplots
1153 self.nplots = nplots
1205
1154
1206 ncolspan = 7
1155 ncolspan = 7
1207 colspan = 6
1156 colspan = 6
1208 self.__nsubplots = 2
1157 self.__nsubplots = 2
1209
1158
1210 self.createFigure(id = id,
1159 self.createFigure(id = id,
1211 wintitle = wintitle,
1160 wintitle = wintitle,
1212 widthplot = self.WIDTH+self.WIDTHPROF,
1161 widthplot = self.WIDTH+self.WIDTHPROF,
1213 heightplot = self.HEIGHT+self.HEIGHTPROF,
1162 heightplot = self.HEIGHT+self.HEIGHTPROF,
1214 show=show)
1163 show=show)
1215
1164
1216 nrow, ncol = self.getSubplots()
1165 nrow, ncol = self.getSubplots()
1217
1166
1218 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1167 self.addAxes(nrow, ncol*ncolspan, 0, 0, colspan, 1)
1219
1168
1220 def save_phase(self, filename_phase):
1169 def save_phase(self, filename_phase):
1221 f = open(filename_phase,'w+')
1170 f = open(filename_phase,'w+')
1222 f.write('\n\n')
1171 f.write('\n\n')
1223 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1172 f.write('JICAMARCA RADIO OBSERVATORY - Beacon Phase \n')
1224 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1173 f.write('DD MM YYYY HH MM SS pair(2,0) pair(2,1) pair(2,3) pair(2,4)\n\n' )
1225 f.close()
1174 f.close()
1226
1175
1227 def save_data(self, filename_phase, data, data_datetime):
1176 def save_data(self, filename_phase, data, data_datetime):
1228 f=open(filename_phase,'a')
1177 f=open(filename_phase,'a')
1229 timetuple_data = data_datetime.timetuple()
1178 timetuple_data = data_datetime.timetuple()
1230 day = str(timetuple_data.tm_mday)
1179 day = str(timetuple_data.tm_mday)
1231 month = str(timetuple_data.tm_mon)
1180 month = str(timetuple_data.tm_mon)
1232 year = str(timetuple_data.tm_year)
1181 year = str(timetuple_data.tm_year)
1233 hour = str(timetuple_data.tm_hour)
1182 hour = str(timetuple_data.tm_hour)
1234 minute = str(timetuple_data.tm_min)
1183 minute = str(timetuple_data.tm_min)
1235 second = str(timetuple_data.tm_sec)
1184 second = str(timetuple_data.tm_sec)
1236 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1185 f.write(day+' '+month+' '+year+' '+hour+' '+minute+' '+second+' '+str(data[0])+' '+str(data[1])+' '+str(data[2])+' '+str(data[3])+'\n')
1237 f.close()
1186 f.close()
1238
1187
1239
1188
1240 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1189 def run(self, dataOut, id, wintitle="", pairsList=None, showprofile='True',
1241 xmin=None, xmax=None, ymin=None, ymax=None,
1190 xmin=None, xmax=None, ymin=None, ymax=None,
1242 timerange=None,
1191 timerange=None,
1243 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1192 save=False, figpath='./', figfile=None, show=True, ftp=False, wr_period=1,
1244 server=None, folder=None, username=None, password=None,
1193 server=None, folder=None, username=None, password=None,
1245 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1194 ftp_wei=0, exp_code=0, sub_exp_code=0, plot_pos=0):
1246
1195
1247 if pairsList == None:
1196 if pairsList == None:
1248 pairsIndexList = dataOut.pairsIndexList
1197 pairsIndexList = dataOut.pairsIndexList
1249 else:
1198 else:
1250 pairsIndexList = []
1199 pairsIndexList = []
1251 for pair in pairsList:
1200 for pair in pairsList:
1252 if pair not in dataOut.pairsList:
1201 if pair not in dataOut.pairsList:
1253 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1202 raise ValueError, "Pair %s is not in dataOut.pairsList" %(pair)
1254 pairsIndexList.append(dataOut.pairsList.index(pair))
1203 pairsIndexList.append(dataOut.pairsList.index(pair))
1255
1204
1256 if pairsIndexList == []:
1205 if pairsIndexList == []:
1257 return
1206 return
1258
1207
1259 # if len(pairsIndexList) > 4:
1208 # if len(pairsIndexList) > 4:
1260 # pairsIndexList = pairsIndexList[0:4]
1209 # pairsIndexList = pairsIndexList[0:4]
1261
1210
1262 x = dataOut.getTimeRange()
1211 x = dataOut.getTimeRange()
1263 #y = dataOut.getHeiRange()
1212 #y = dataOut.getHeiRange()
1264
1213
1265
1214
1266 #thisDatetime = dataOut.datatime
1215 #thisDatetime = dataOut.datatime
1267 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1216 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
1268 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1217 title = wintitle + " Phase of Beacon Signal" # : %s" %(thisDatetime.strftime("%d-%b-%Y"))
1269 xlabel = "Local Time"
1218 xlabel = "Local Time"
1270 ylabel = "Phase"
1219 ylabel = "Phase"
1271
1220
1272 nplots = len(pairsIndexList)
1221 nplots = len(pairsIndexList)
1273 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1222 #phase = numpy.zeros((len(pairsIndexList),len(dataOut.beacon_heiIndexList)))
1274 phase_beacon = numpy.zeros(len(pairsIndexList))
1223 phase_beacon = numpy.zeros(len(pairsIndexList))
1275 for i in range(nplots):
1224 for i in range(nplots):
1276 pair = dataOut.pairsList[pairsIndexList[i]]
1225 pair = dataOut.pairsList[pairsIndexList[i]]
1277 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
1226 ccf = numpy.average(dataOut.data_cspc[pairsIndexList[i],:,:],axis=0)
1278 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
1227 powa = numpy.average(dataOut.data_spc[pair[0],:,:],axis=0)
1279 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
1228 powb = numpy.average(dataOut.data_spc[pair[1],:,:],axis=0)
1280 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1229 avgcoherenceComplex = ccf/numpy.sqrt(powa*powb)
1281 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1230 phase = numpy.arctan2(avgcoherenceComplex.imag, avgcoherenceComplex.real)*180/numpy.pi
1282
1231
1283 #print "Phase %d%d" %(pair[0], pair[1])
1232 #print "Phase %d%d" %(pair[0], pair[1])
1284 #print phase[dataOut.beacon_heiIndexList]
1233 #print phase[dataOut.beacon_heiIndexList]
1285
1234
1286 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1235 phase_beacon[i] = numpy.average(phase[dataOut.beacon_heiIndexList])
1287
1236
1288 if not self.__isConfig:
1237 if not self.__isConfig:
1289
1238
1290 nplots = len(pairsIndexList)
1239 nplots = len(pairsIndexList)
1291
1240
1292 self.setup(id=id,
1241 self.setup(id=id,
1293 nplots=nplots,
1242 nplots=nplots,
1294 wintitle=wintitle,
1243 wintitle=wintitle,
1295 showprofile=showprofile,
1244 showprofile=showprofile,
1296 show=show)
1245 show=show)
1297
1246
1298 if timerange != None:
1247 if timerange != None:
1299 self.timerange = timerange
1248 self.timerange = timerange
1300
1249
1301 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1250 self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange)
1302
1251
1303 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1252 if ymin == None: ymin = numpy.nanmin(phase_beacon) - 10.0
1304 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1253 if ymax == None: ymax = numpy.nanmax(phase_beacon) + 10.0
1305
1254
1306 self.FTP_WEI = ftp_wei
1255 self.FTP_WEI = ftp_wei
1307 self.EXP_CODE = exp_code
1256 self.EXP_CODE = exp_code
1308 self.SUB_EXP_CODE = sub_exp_code
1257 self.SUB_EXP_CODE = sub_exp_code
1309 self.PLOT_POS = plot_pos
1258 self.PLOT_POS = plot_pos
1310
1259
1311 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1260 self.name = thisDatetime.strftime("%Y%m%d_%H%M%S")
1312 self.__isConfig = True
1261 self.__isConfig = True
1313 self.figfile = figfile
1262 self.figfile = figfile
1314 self.xdata = numpy.array([])
1263 self.xdata = numpy.array([])
1315 self.ydata = numpy.array([])
1264 self.ydata = numpy.array([])
1316
1265
1317 #open file beacon phase
1266 #open file beacon phase
1318 path = '%s%03d' %(self.PREFIX, self.id)
1267 path = '%s%03d' %(self.PREFIX, self.id)
1319 beacon_file = os.path.join(path,'%s.txt'%self.name)
1268 beacon_file = os.path.join(path,'%s.txt'%self.name)
1320 self.filename_phase = os.path.join(figpath,beacon_file)
1269 self.filename_phase = os.path.join(figpath,beacon_file)
1321 #self.save_phase(self.filename_phase)
1270 #self.save_phase(self.filename_phase)
1322
1271
1323
1272
1324 #store data beacon phase
1273 #store data beacon phase
1325 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1274 #self.save_data(self.filename_phase, phase_beacon, thisDatetime)
1326
1275
1327 self.setWinTitle(title)
1276 self.setWinTitle(title)
1328
1277
1329
1278
1330 title = "Beacon Signal %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1279 title = "Beacon Signal %s" %(thisDatetime.strftime("%Y/%m/%d %H:%M:%S"))
1331
1280
1332 legendlabels = ["pairs %d%d"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1281 legendlabels = ["pairs %d%d"%(pair[0], pair[1]) for pair in dataOut.pairsList]
1333
1282
1334 axes = self.axesList[0]
1283 axes = self.axesList[0]
1335
1284
1336 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1285 self.xdata = numpy.hstack((self.xdata, x[0:1]))
1337
1286
1338 if len(self.ydata)==0:
1287 if len(self.ydata)==0:
1339 self.ydata = phase_beacon.reshape(-1,1)
1288 self.ydata = phase_beacon.reshape(-1,1)
1340 else:
1289 else:
1341 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1290 self.ydata = numpy.hstack((self.ydata, phase_beacon.reshape(-1,1)))
1342
1291
1343
1292
1344 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1293 axes.pmultilineyaxis(x=self.xdata, y=self.ydata,
1345 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1294 xmin=self.xmin, xmax=self.xmax, ymin=ymin, ymax=ymax,
1346 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1295 xlabel=xlabel, ylabel=ylabel, title=title, legendlabels=legendlabels, marker='x', markersize=8, linestyle="solid",
1347 XAxisAsTime=True, grid='both'
1296 XAxisAsTime=True, grid='both'
1348 )
1297 )
1349
1298
1350 self.draw()
1299 self.draw()
1351
1300
1352 if x[1] >= self.axesList[0].xmax:
1301 if x[1] >= self.axesList[0].xmax:
1353 self.counter_imagwr = wr_period
1302 self.counter_imagwr = wr_period
1354 del self.xdata
1303 del self.xdata
1355 del self.ydata
1304 del self.ydata
1356 self.__isConfig = False
1305 self.__isConfig = False
1357
1306 self.figfile = None
1358 if save:
1359
1360 if self.figfile == None:
1361 str_datetime = thisDatetime.strftime("%Y%m%d_%H%M%S")
1362 self.figfile = self.getFilename(name = str_datetime)
1363
1364 self.counter_imagwr += 1
1365
1307
1366 if (self.counter_imagwr>=wr_period):
1308 self.save(figpath=figpath,
1367 # store png plot to local folder
1309 figfile=figfile,
1368 self.saveFigure(figpath, self.figfile)
1310 save=save,
1369 self.counter_imagwr = 0
1311 ftp=ftp,
1370
1312 wr_period=wr_period,
1371 if ftp:
1313 thisDatetime=thisDatetime,
1372 # store png plot to FTP server according to RT-Web format
1314 update_figfile=False)
1373 name = self.getNameToFtp(thisDatetime, self.FTP_WEI, self.EXP_CODE, self.SUB_EXP_CODE, self.PLOT_CODE, self.PLOT_POS)
1374 ftp_filename = os.path.join(figpath, name)
1375 self.saveFigure(figpath, ftp_filename)
@@ -1,186 +1,180
1 '''
1 '''
2 Created on Jul 9, 2014
2 Created on Jul 9, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import datetime
7 import datetime
8 import numpy
8 import numpy
9
9
10 from figure import Figure
10 from figure import Figure
11
11
12 class Scope(Figure):
12 class Scope(Figure):
13
13
14 isConfig = None
14 isConfig = None
15
15
16 def __init__(self):
16 def __init__(self):
17
17
18 self.isConfig = False
18 self.isConfig = False
19 self.WIDTH = 300
19 self.WIDTH = 300
20 self.HEIGHT = 200
20 self.HEIGHT = 200
21 self.counter_imagwr = 0
21 self.counter_imagwr = 0
22
22
23 def getSubplots(self):
23 def getSubplots(self):
24
24
25 nrow = self.nplots
25 nrow = self.nplots
26 ncol = 3
26 ncol = 3
27 return nrow, ncol
27 return nrow, ncol
28
28
29 def setup(self, id, nplots, wintitle, show):
29 def setup(self, id, nplots, wintitle, show):
30
30
31 self.nplots = nplots
31 self.nplots = nplots
32
32
33 self.createFigure(id=id,
33 self.createFigure(id=id,
34 wintitle=wintitle,
34 wintitle=wintitle,
35 show=show)
35 show=show)
36
36
37 nrow,ncol = self.getSubplots()
37 nrow,ncol = self.getSubplots()
38 colspan = 3
38 colspan = 3
39 rowspan = 1
39 rowspan = 1
40
40
41 for i in range(nplots):
41 for i in range(nplots):
42 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
42 self.addAxes(nrow, ncol, i, 0, colspan, rowspan)
43
43
44 def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
44 def plot_iq(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
45 yreal = y[channelIndexList,:].real
45 yreal = y[channelIndexList,:].real
46 yimag = y[channelIndexList,:].imag
46 yimag = y[channelIndexList,:].imag
47
47
48 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
48 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
49 xlabel = "Range (Km)"
49 xlabel = "Range (Km)"
50 ylabel = "Intensity - IQ"
50 ylabel = "Intensity - IQ"
51
51
52 if not self.isConfig:
52 if not self.isConfig:
53 nplots = len(channelIndexList)
53 nplots = len(channelIndexList)
54
54
55 self.setup(id=id,
55 self.setup(id=id,
56 nplots=nplots,
56 nplots=nplots,
57 wintitle='',
57 wintitle='',
58 show=show)
58 show=show)
59
59
60 if xmin == None: xmin = numpy.nanmin(x)
60 if xmin == None: xmin = numpy.nanmin(x)
61 if xmax == None: xmax = numpy.nanmax(x)
61 if xmax == None: xmax = numpy.nanmax(x)
62 if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag))
62 if ymin == None: ymin = min(numpy.nanmin(yreal),numpy.nanmin(yimag))
63 if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag))
63 if ymax == None: ymax = max(numpy.nanmax(yreal),numpy.nanmax(yimag))
64
64
65 self.isConfig = True
65 self.isConfig = True
66
66
67 self.setWinTitle(title)
67 self.setWinTitle(title)
68
68
69 for i in range(len(self.axesList)):
69 for i in range(len(self.axesList)):
70 title = "Channel %d" %(i)
70 title = "Channel %d" %(i)
71 axes = self.axesList[i]
71 axes = self.axesList[i]
72
72
73 axes.pline(x, yreal[i,:],
73 axes.pline(x, yreal[i,:],
74 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
74 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
75 xlabel=xlabel, ylabel=ylabel, title=title)
75 xlabel=xlabel, ylabel=ylabel, title=title)
76
76
77 axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2)
77 axes.addpline(x, yimag[i,:], idline=1, color="red", linestyle="solid", lw=2)
78
78
79 def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
79 def plot_power(self, x, y, id, channelIndexList, thisDatetime, wintitle, show, xmin, xmax, ymin, ymax):
80 y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:])
80 y = y[channelIndexList,:] * numpy.conjugate(y[channelIndexList,:])
81 yreal = y.real
81 yreal = y.real
82
82
83 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
83 title = wintitle + " Scope: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S"))
84 xlabel = "Range (Km)"
84 xlabel = "Range (Km)"
85 ylabel = "Intensity"
85 ylabel = "Intensity"
86
86
87 if not self.isConfig:
87 if not self.isConfig:
88 nplots = len(channelIndexList)
88 nplots = len(channelIndexList)
89
89
90 self.setup(id=id,
90 self.setup(id=id,
91 nplots=nplots,
91 nplots=nplots,
92 wintitle='',
92 wintitle='',
93 show=show)
93 show=show)
94
94
95 if xmin == None: xmin = numpy.nanmin(x)
95 if xmin == None: xmin = numpy.nanmin(x)
96 if xmax == None: xmax = numpy.nanmax(x)
96 if xmax == None: xmax = numpy.nanmax(x)
97 if ymin == None: ymin = numpy.nanmin(yreal)
97 if ymin == None: ymin = numpy.nanmin(yreal)
98 if ymax == None: ymax = numpy.nanmax(yreal)
98 if ymax == None: ymax = numpy.nanmax(yreal)
99
99
100 self.isConfig = True
100 self.isConfig = True
101
101
102 self.setWinTitle(title)
102 self.setWinTitle(title)
103
103
104 for i in range(len(self.axesList)):
104 for i in range(len(self.axesList)):
105 title = "Channel %d" %(i)
105 title = "Channel %d" %(i)
106 axes = self.axesList[i]
106 axes = self.axesList[i]
107 ychannel = yreal[i,:]
107 ychannel = yreal[i,:]
108 axes.pline(x, ychannel,
108 axes.pline(x, ychannel,
109 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
109 xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,
110 xlabel=xlabel, ylabel=ylabel, title=title)
110 xlabel=xlabel, ylabel=ylabel, title=title)
111
111
112
112
113 def run(self, dataOut, id, wintitle="", channelList=None,
113 def run(self, dataOut, id, wintitle="", channelList=None,
114 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
114 xmin=None, xmax=None, ymin=None, ymax=None, save=False,
115 figpath='./', figfile=None, show=True, wr_period=1,
115 figpath='./', figfile=None, show=True, wr_period=1,
116 ftp=False, server=None, folder=None, username=None, password=None, type='power'):
116 ftp=False, server=None, folder=None, username=None, password=None, type='power'):
117
117
118 """
118 """
119
119
120 Input:
120 Input:
121 dataOut :
121 dataOut :
122 id :
122 id :
123 wintitle :
123 wintitle :
124 channelList :
124 channelList :
125 xmin : None,
125 xmin : None,
126 xmax : None,
126 xmax : None,
127 ymin : None,
127 ymin : None,
128 ymax : None,
128 ymax : None,
129 """
129 """
130
130
131 if channelList == None:
131 if channelList == None:
132 channelIndexList = dataOut.channelIndexList
132 channelIndexList = dataOut.channelIndexList
133 else:
133 else:
134 channelIndexList = []
134 channelIndexList = []
135 for channel in channelList:
135 for channel in channelList:
136 if channel not in dataOut.channelList:
136 if channel not in dataOut.channelList:
137 raise ValueError, "Channel %d is not in dataOut.channelList"
137 raise ValueError, "Channel %d is not in dataOut.channelList"
138 channelIndexList.append(dataOut.channelList.index(channel))
138 channelIndexList.append(dataOut.channelList.index(channel))
139
139
140 x = dataOut.heightList
140 x = dataOut.heightList
141 y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
141 y = dataOut.data[channelIndexList,:] * numpy.conjugate(dataOut.data[channelIndexList,:])
142 y = y.real
142 y = y.real
143
143
144 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
144 thisDatetime = datetime.datetime.utcfromtimestamp(dataOut.getTimeRange()[0])
145
145
146 if type == "power":
146 if type == "power":
147 self.plot_power(dataOut.heightList,
147 self.plot_power(dataOut.heightList,
148 dataOut.data,
148 dataOut.data,
149 id,
149 id,
150 channelIndexList,
150 channelIndexList,
151 thisDatetime,
151 thisDatetime,
152 wintitle,
152 wintitle,
153 show,
153 show,
154 xmin,
154 xmin,
155 xmax,
155 xmax,
156 ymin,
156 ymin,
157 ymax)
157 ymax)
158
158
159 if type == "iq":
159 if type == "iq":
160 self.plot_iq(dataOut.heightList,
160 self.plot_iq(dataOut.heightList,
161 dataOut.data,
161 dataOut.data,
162 id,
162 id,
163 channelIndexList,
163 channelIndexList,
164 thisDatetime,
164 thisDatetime,
165 wintitle,
165 wintitle,
166 show,
166 show,
167 xmin,
167 xmin,
168 xmax,
168 xmax,
169 ymin,
169 ymin,
170 ymax)
170 ymax)
171
171
172
172
173 self.draw()
173 self.draw()
174
174
175 if save:
175 self.save(figpath=figpath,
176 date = thisDatetime.strftime("%Y%m%d_%H%M%S")
176 figfile=figfile,
177 if figfile == None:
177 save=save,
178 figfile = self.getFilename(name = date)
178 ftp=ftp,
179
179 wr_period=wr_period,
180 self.saveFigure(figpath, figfile)
180 thisDatetime=thisDatetime)
181
182 self.counter_imagwr += 1
183 if (ftp and (self.counter_imagwr==wr_period)):
184 ftp_filename = os.path.join(figpath,figfile)
185 self.sendByFTP_Thread(ftp_filename, server, folder, username, password)
186 self.counter_imagwr = 0
@@ -1,1345 +1,1345
1 '''
1 '''
2 Created on Jul 2, 2014
2 Created on Jul 2, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import os
6 import os
7 import sys
7 import sys
8 import glob
8 import glob
9 import time
9 import time
10 import numpy
10 import numpy
11 import fnmatch
11 import fnmatch
12 import time, datetime
12 import time, datetime
13 #import h5py
13 #import h5py
14 import traceback
14 import traceback
15
15
16 try:
16 try:
17 from gevent import sleep
17 from gevent import sleep
18 except:
18 except:
19 from time import sleep
19 from time import sleep
20
20
21 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
21 from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader
22
22
23 LOCALTIME = True
23 LOCALTIME = True
24
24
25 def isNumber(cad):
25 def isNumber(cad):
26 """
26 """
27 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
27 Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero.
28
28
29 Excepciones:
29 Excepciones:
30 Si un determinado string no puede ser convertido a numero
30 Si un determinado string no puede ser convertido a numero
31 Input:
31 Input:
32 str, string al cual se le analiza para determinar si convertible a un numero o no
32 str, string al cual se le analiza para determinar si convertible a un numero o no
33
33
34 Return:
34 Return:
35 True : si el string es uno numerico
35 True : si el string es uno numerico
36 False : no es un string numerico
36 False : no es un string numerico
37 """
37 """
38 try:
38 try:
39 float( cad )
39 float( cad )
40 return True
40 return True
41 except:
41 except:
42 return False
42 return False
43
43
44 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
44 def isThisFileinRange(filename, startUTSeconds, endUTSeconds):
45 """
45 """
46 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
46 Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado.
47
47
48 Inputs:
48 Inputs:
49 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
49 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
50
50
51 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
51 startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en
52 segundos contados desde 01/01/1970.
52 segundos contados desde 01/01/1970.
53 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
53 endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en
54 segundos contados desde 01/01/1970.
54 segundos contados desde 01/01/1970.
55
55
56 Return:
56 Return:
57 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
57 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
58 fecha especificado, de lo contrario retorna False.
58 fecha especificado, de lo contrario retorna False.
59
59
60 Excepciones:
60 Excepciones:
61 Si el archivo no existe o no puede ser abierto
61 Si el archivo no existe o no puede ser abierto
62 Si la cabecera no puede ser leida.
62 Si la cabecera no puede ser leida.
63
63
64 """
64 """
65 basicHeaderObj = BasicHeader(LOCALTIME)
65 basicHeaderObj = BasicHeader(LOCALTIME)
66
66
67 try:
67 try:
68 fp = open(filename,'rb')
68 fp = open(filename,'rb')
69 except IOError:
69 except IOError:
70 traceback.print_exc()
70 traceback.print_exc()
71 raise IOError, "The file %s can't be opened" %(filename)
71 raise IOError, "The file %s can't be opened" %(filename)
72
72
73 sts = basicHeaderObj.read(fp)
73 sts = basicHeaderObj.read(fp)
74 fp.close()
74 fp.close()
75
75
76 if not(sts):
76 if not(sts):
77 print "Skipping the file %s because it has not a valid header" %(filename)
77 print "Skipping the file %s because it has not a valid header" %(filename)
78 return 0
78 return 0
79
79
80 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
80 if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)):
81 return 0
81 return 0
82
82
83 return 1
83 return 1
84
84
85 def isFileinThisTime(filename, startTime, endTime):
85 def isFileinThisTime(filename, startTime, endTime):
86 """
86 """
87 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
87 Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado.
88
88
89 Inputs:
89 Inputs:
90 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
90 filename : nombre completo del archivo de datos en formato Jicamarca (.r)
91
91
92 startTime : tiempo inicial del rango seleccionado en formato datetime.time
92 startTime : tiempo inicial del rango seleccionado en formato datetime.time
93
93
94 endTime : tiempo final del rango seleccionado en formato datetime.time
94 endTime : tiempo final del rango seleccionado en formato datetime.time
95
95
96 Return:
96 Return:
97 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
97 Boolean : Retorna True si el archivo de datos contiene datos en el rango de
98 fecha especificado, de lo contrario retorna False.
98 fecha especificado, de lo contrario retorna False.
99
99
100 Excepciones:
100 Excepciones:
101 Si el archivo no existe o no puede ser abierto
101 Si el archivo no existe o no puede ser abierto
102 Si la cabecera no puede ser leida.
102 Si la cabecera no puede ser leida.
103
103
104 """
104 """
105
105
106
106
107 try:
107 try:
108 fp = open(filename,'rb')
108 fp = open(filename,'rb')
109 except IOError:
109 except IOError:
110 traceback.print_exc()
110 traceback.print_exc()
111 raise IOError, "The file %s can't be opened" %(filename)
111 raise IOError, "The file %s can't be opened" %(filename)
112
112
113 basicHeaderObj = BasicHeader(LOCALTIME)
113 basicHeaderObj = BasicHeader(LOCALTIME)
114 sts = basicHeaderObj.read(fp)
114 sts = basicHeaderObj.read(fp)
115 fp.close()
115 fp.close()
116
116
117 thisDatetime = basicHeaderObj.datatime
117 thisDatetime = basicHeaderObj.datatime
118 thisTime = thisDatetime.time()
118 thisTime = thisDatetime.time()
119
119
120 if not(sts):
120 if not(sts):
121 print "Skipping the file %s because it has not a valid header" %(filename)
121 print "Skipping the file %s because it has not a valid header" %(filename)
122 return None
122 return None
123
123
124 if not ((startTime <= thisTime) and (endTime > thisTime)):
124 if not ((startTime <= thisTime) and (endTime > thisTime)):
125 return None
125 return None
126
126
127 return thisDatetime
127 return thisDatetime
128
128
129 def getFileFromSet(path, ext, set):
129 def getFileFromSet(path, ext, set):
130 validFilelist = []
130 validFilelist = []
131 fileList = os.listdir(path)
131 fileList = os.listdir(path)
132
132
133 # 0 1234 567 89A BCDE
133 # 0 1234 567 89A BCDE
134 # H YYYY DDD SSS .ext
134 # H YYYY DDD SSS .ext
135
135
136 for thisFile in fileList:
136 for thisFile in fileList:
137 try:
137 try:
138 year = int(thisFile[1:5])
138 year = int(thisFile[1:5])
139 doy = int(thisFile[5:8])
139 doy = int(thisFile[5:8])
140 except:
140 except:
141 continue
141 continue
142
142
143 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
143 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
144 continue
144 continue
145
145
146 validFilelist.append(thisFile)
146 validFilelist.append(thisFile)
147
147
148 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
148 myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set))
149
149
150 if len(myfile)!= 0:
150 if len(myfile)!= 0:
151 return myfile[0]
151 return myfile[0]
152 else:
152 else:
153 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
153 filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower())
154 print 'the filename %s does not exist'%filename
154 print 'the filename %s does not exist'%filename
155 print '...going to the last file: '
155 print '...going to the last file: '
156
156
157 if validFilelist:
157 if validFilelist:
158 validFilelist = sorted( validFilelist, key=str.lower )
158 validFilelist = sorted( validFilelist, key=str.lower )
159 return validFilelist[-1]
159 return validFilelist[-1]
160
160
161 return None
161 return None
162
162
163 def getlastFileFromPath(path, ext):
163 def getlastFileFromPath(path, ext):
164 """
164 """
165 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
165 Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext"
166 al final de la depuracion devuelve el ultimo file de la lista que quedo.
166 al final de la depuracion devuelve el ultimo file de la lista que quedo.
167
167
168 Input:
168 Input:
169 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
169 fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta
170 ext : extension de los files contenidos en una carpeta
170 ext : extension de los files contenidos en una carpeta
171
171
172 Return:
172 Return:
173 El ultimo file de una determinada carpeta, no se considera el path.
173 El ultimo file de una determinada carpeta, no se considera el path.
174 """
174 """
175 validFilelist = []
175 validFilelist = []
176 fileList = os.listdir(path)
176 fileList = os.listdir(path)
177
177
178 # 0 1234 567 89A BCDE
178 # 0 1234 567 89A BCDE
179 # H YYYY DDD SSS .ext
179 # H YYYY DDD SSS .ext
180
180
181 for thisFile in fileList:
181 for thisFile in fileList:
182
182
183 year = thisFile[1:5]
183 year = thisFile[1:5]
184 if not isNumber(year):
184 if not isNumber(year):
185 continue
185 continue
186
186
187 doy = thisFile[5:8]
187 doy = thisFile[5:8]
188 if not isNumber(doy):
188 if not isNumber(doy):
189 continue
189 continue
190
190
191 year = int(year)
191 year = int(year)
192 doy = int(doy)
192 doy = int(doy)
193
193
194 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
194 if (os.path.splitext(thisFile)[-1].lower() != ext.lower()):
195 continue
195 continue
196
196
197 validFilelist.append(thisFile)
197 validFilelist.append(thisFile)
198
198
199 if validFilelist:
199 if validFilelist:
200 validFilelist = sorted( validFilelist, key=str.lower )
200 validFilelist = sorted( validFilelist, key=str.lower )
201 return validFilelist[-1]
201 return validFilelist[-1]
202
202
203 return None
203 return None
204
204
205 def checkForRealPath(path, foldercounter, year, doy, set, ext):
205 def checkForRealPath(path, foldercounter, year, doy, set, ext):
206 """
206 """
207 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
207 Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path,
208 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
208 Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar
209 el path exacto de un determinado file.
209 el path exacto de un determinado file.
210
210
211 Example :
211 Example :
212 nombre correcto del file es .../.../D2009307/P2009307367.ext
212 nombre correcto del file es .../.../D2009307/P2009307367.ext
213
213
214 Entonces la funcion prueba con las siguientes combinaciones
214 Entonces la funcion prueba con las siguientes combinaciones
215 .../.../y2009307367.ext
215 .../.../y2009307367.ext
216 .../.../Y2009307367.ext
216 .../.../Y2009307367.ext
217 .../.../x2009307/y2009307367.ext
217 .../.../x2009307/y2009307367.ext
218 .../.../x2009307/Y2009307367.ext
218 .../.../x2009307/Y2009307367.ext
219 .../.../X2009307/y2009307367.ext
219 .../.../X2009307/y2009307367.ext
220 .../.../X2009307/Y2009307367.ext
220 .../.../X2009307/Y2009307367.ext
221 siendo para este caso, la ultima combinacion de letras, identica al file buscado
221 siendo para este caso, la ultima combinacion de letras, identica al file buscado
222
222
223 Return:
223 Return:
224 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
224 Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file
225 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
225 caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas
226 para el filename
226 para el filename
227 """
227 """
228 fullfilename = None
228 fullfilename = None
229 find_flag = False
229 find_flag = False
230 filename = None
230 filename = None
231
231
232 prefixDirList = [None,'d','D']
232 prefixDirList = [None,'d','D']
233 if ext.lower() == ".r": #voltage
233 if ext.lower() == ".r": #voltage
234 prefixFileList = ['d','D']
234 prefixFileList = ['d','D']
235 elif ext.lower() == ".pdata": #spectra
235 elif ext.lower() == ".pdata": #spectra
236 prefixFileList = ['p','P']
236 prefixFileList = ['p','P']
237 else:
237 else:
238 return None, filename
238 return None, filename
239
239
240 #barrido por las combinaciones posibles
240 #barrido por las combinaciones posibles
241 for prefixDir in prefixDirList:
241 for prefixDir in prefixDirList:
242 thispath = path
242 thispath = path
243 if prefixDir != None:
243 if prefixDir != None:
244 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
244 #formo el nombre del directorio xYYYYDDD (x=d o x=D)
245 if foldercounter == 0:
245 if foldercounter == 0:
246 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
246 thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy ))
247 else:
247 else:
248 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
248 thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter))
249 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
249 for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D"
250 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
250 filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext
251 fullfilename = os.path.join( thispath, filename ) #formo el path completo
251 fullfilename = os.path.join( thispath, filename ) #formo el path completo
252
252
253 if os.path.exists( fullfilename ): #verifico que exista
253 if os.path.exists( fullfilename ): #verifico que exista
254 find_flag = True
254 find_flag = True
255 break
255 break
256 if find_flag:
256 if find_flag:
257 break
257 break
258
258
259 if not(find_flag):
259 if not(find_flag):
260 return None, filename
260 return None, filename
261
261
262 return fullfilename, filename
262 return fullfilename, filename
263
263
264 def isDoyFolder(folder):
264 def isDoyFolder(folder):
265 try:
265 try:
266 year = int(folder[1:5])
266 year = int(folder[1:5])
267 except:
267 except:
268 return 0
268 return 0
269
269
270 try:
270 try:
271 doy = int(folder[5:8])
271 doy = int(folder[5:8])
272 except:
272 except:
273 return 0
273 return 0
274
274
275 return 1
275 return 1
276
276
277 class JRODataIO:
277 class JRODataIO:
278
278
279 c = 3E8
279 c = 3E8
280
280
281 isConfig = False
281 isConfig = False
282
282
283 basicHeaderObj = None
283 basicHeaderObj = None
284
284
285 systemHeaderObj = None
285 systemHeaderObj = None
286
286
287 radarControllerHeaderObj = None
287 radarControllerHeaderObj = None
288
288
289 processingHeaderObj = None
289 processingHeaderObj = None
290
290
291 online = 0
291 online = 0
292
292
293 dtype = None
293 dtype = None
294
294
295 pathList = []
295 pathList = []
296
296
297 filenameList = []
297 filenameList = []
298
298
299 filename = None
299 filename = None
300
300
301 ext = None
301 ext = None
302
302
303 flagIsNewFile = 1
303 flagIsNewFile = 1
304
304
305 flagDiscontinuousBlock = 0
305 flagDiscontinuousBlock = 0
306
306
307 flagIsNewBlock = 0
307 flagIsNewBlock = 0
308
308
309 fp = None
309 fp = None
310
310
311 firstHeaderSize = 0
311 firstHeaderSize = 0
312
312
313 basicHeaderSize = 24
313 basicHeaderSize = 24
314
314
315 versionFile = 1103
315 versionFile = 1103
316
316
317 fileSize = None
317 fileSize = None
318
318
319 # ippSeconds = None
319 # ippSeconds = None
320
320
321 fileSizeByHeader = None
321 fileSizeByHeader = None
322
322
323 fileIndex = None
323 fileIndex = None
324
324
325 profileIndex = None
325 profileIndex = None
326
326
327 blockIndex = None
327 blockIndex = None
328
328
329 nTotalBlocks = None
329 nTotalBlocks = None
330
330
331 maxTimeStep = 30
331 maxTimeStep = 30
332
332
333 lastUTTime = None
333 lastUTTime = None
334
334
335 datablock = None
335 datablock = None
336
336
337 dataOut = None
337 dataOut = None
338
338
339 blocksize = None
339 blocksize = None
340
340
341 getByBlock = False
341 getByBlock = False
342
342
343 def __init__(self):
343 def __init__(self):
344
344
345 raise ValueError, "Not implemented"
345 raise ValueError, "Not implemented"
346
346
347 def run(self):
347 def run(self):
348
348
349 raise ValueError, "Not implemented"
349 raise ValueError, "Not implemented"
350
350
351 class JRODataReader(JRODataIO):
351 class JRODataReader(JRODataIO):
352
352
353 nReadBlocks = 0
353 nReadBlocks = 0
354
354
355 delay = 10 #number of seconds waiting a new file
355 delay = 10 #number of seconds waiting a new file
356
356
357 nTries = 3 #quantity tries
357 nTries = 3 #quantity tries
358
358
359 nFiles = 3 #number of files for searching
359 nFiles = 3 #number of files for searching
360
360
361 path = None
361 path = None
362
362
363 foldercounter = 0
363 foldercounter = 0
364
364
365 flagNoMoreFiles = 0
365 flagNoMoreFiles = 0
366
366
367 datetimeList = []
367 datetimeList = []
368
368
369 __isFirstTimeOnline = 1
369 __isFirstTimeOnline = 1
370
370
371 __printInfo = True
371 __printInfo = True
372
372
373 profileIndex = None
373 profileIndex = None
374
374
375 nTxs = 1
375 nTxs = 1
376
376
377 txIndex = None
377 txIndex = None
378
378
379 def __init__(self):
379 def __init__(self):
380
380
381 """
381 """
382
382
383 """
383 """
384
384
385 raise ValueError, "This method has not been implemented"
385 raise ValueError, "This method has not been implemented"
386
386
387
387
388 def createObjByDefault(self):
388 def createObjByDefault(self):
389 """
389 """
390
390
391 """
391 """
392 raise ValueError, "This method has not been implemented"
392 raise ValueError, "This method has not been implemented"
393
393
394 def getBlockDimension(self):
394 def getBlockDimension(self):
395
395
396 raise ValueError, "No implemented"
396 raise ValueError, "No implemented"
397
397
398 def __searchFilesOffLine(self,
398 def __searchFilesOffLine(self,
399 path,
399 path,
400 startDate,
400 startDate,
401 endDate,
401 endDate,
402 startTime=datetime.time(0,0,0),
402 startTime=datetime.time(0,0,0),
403 endTime=datetime.time(23,59,59),
403 endTime=datetime.time(23,59,59),
404 set=None,
404 set=None,
405 expLabel='',
405 expLabel='',
406 ext='.r',
406 ext='.r',
407 walk=True):
407 walk=True):
408
408
409 pathList = []
409 pathList = []
410
410
411 if not walk:
411 if not walk:
412 #pathList.append(path)
412 #pathList.append(path)
413 multi_path = path.split(',')
413 multi_path = path.split(',')
414 for single_path in multi_path:
414 for single_path in multi_path:
415 pathList.append(single_path)
415 pathList.append(single_path)
416
416
417 else:
417 else:
418 #dirList = []
418 #dirList = []
419 multi_path = path.split(',')
419 multi_path = path.split(',')
420 for single_path in multi_path:
420 for single_path in multi_path:
421 dirList = []
421 dirList = []
422 for thisPath in os.listdir(single_path):
422 for thisPath in os.listdir(single_path):
423 if not os.path.isdir(os.path.join(single_path,thisPath)):
423 if not os.path.isdir(os.path.join(single_path,thisPath)):
424 continue
424 continue
425 if not isDoyFolder(thisPath):
425 if not isDoyFolder(thisPath):
426 continue
426 continue
427
427
428 dirList.append(thisPath)
428 dirList.append(thisPath)
429
429
430 if not(dirList):
430 if not(dirList):
431 return None, None
431 return None, None
432
432
433 thisDate = startDate
433 thisDate = startDate
434
434
435 while(thisDate <= endDate):
435 while(thisDate <= endDate):
436 year = thisDate.timetuple().tm_year
436 year = thisDate.timetuple().tm_year
437 doy = thisDate.timetuple().tm_yday
437 doy = thisDate.timetuple().tm_yday
438
438
439 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
439 matchlist = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy) + '*')
440 if len(matchlist) == 0:
440 if len(matchlist) == 0:
441 thisDate += datetime.timedelta(1)
441 thisDate += datetime.timedelta(1)
442 continue
442 continue
443 for match in matchlist:
443 for match in matchlist:
444 pathList.append(os.path.join(single_path,match,expLabel))
444 pathList.append(os.path.join(single_path,match,expLabel))
445
445
446 thisDate += datetime.timedelta(1)
446 thisDate += datetime.timedelta(1)
447
447
448 if pathList == []:
448 if pathList == []:
449 print "Any folder was found for the date range: %s-%s" %(startDate, endDate)
449 print "Any folder was found for the date range: %s-%s" %(startDate, endDate)
450 return None, None
450 return None, None
451
451
452 print "%d folder(s) was(were) found for the date range: %s - %s" %(len(pathList), startDate, endDate)
452 print "%d folder(s) was(were) found for the date range: %s - %s" %(len(pathList), startDate, endDate)
453
453
454 filenameList = []
454 filenameList = []
455 datetimeList = []
455 datetimeList = []
456 pathDict = {}
456 pathDict = {}
457 filenameList_to_sort = []
457 filenameList_to_sort = []
458
458
459 for i in range(len(pathList)):
459 for i in range(len(pathList)):
460
460
461 thisPath = pathList[i]
461 thisPath = pathList[i]
462
462
463 fileList = glob.glob1(thisPath, "*%s" %ext)
463 fileList = glob.glob1(thisPath, "*%s" %ext)
464 if len(fileList) < 1:
464 if len(fileList) < 1:
465 continue
465 continue
466 fileList.sort()
466 fileList.sort()
467 pathDict.setdefault(fileList[0])
467 pathDict.setdefault(fileList[0])
468 pathDict[fileList[0]] = i
468 pathDict[fileList[0]] = i
469 filenameList_to_sort.append(fileList[0])
469 filenameList_to_sort.append(fileList[0])
470
470
471 filenameList_to_sort.sort()
471 filenameList_to_sort.sort()
472
472
473 for file in filenameList_to_sort:
473 for file in filenameList_to_sort:
474 thisPath = pathList[pathDict[file]]
474 thisPath = pathList[pathDict[file]]
475
475
476 fileList = glob.glob1(thisPath, "*%s" %ext)
476 fileList = glob.glob1(thisPath, "*%s" %ext)
477 fileList.sort()
477 fileList.sort()
478
478
479 for file in fileList:
479 for file in fileList:
480
480
481 filename = os.path.join(thisPath,file)
481 filename = os.path.join(thisPath,file)
482 thisDatetime = isFileinThisTime(filename, startTime, endTime)
482 thisDatetime = isFileinThisTime(filename, startTime, endTime)
483
483
484 if not(thisDatetime):
484 if not(thisDatetime):
485 continue
485 continue
486
486
487 filenameList.append(filename)
487 filenameList.append(filename)
488 datetimeList.append(thisDatetime)
488 datetimeList.append(thisDatetime)
489
489
490 if not(filenameList):
490 if not(filenameList):
491 print "Any file was found for the time range %s - %s" %(startTime, endTime)
491 print "Any file was found for the time range %s - %s" %(startTime, endTime)
492 return None, None
492 return None, None
493
493
494 print "%d file(s) was(were) found for the time range: %s - %s" %(len(filenameList), startTime, endTime)
494 print "%d file(s) was(were) found for the time range: %s - %s" %(len(filenameList), startTime, endTime)
495 print
495 print
496
496
497 for i in range(len(filenameList)):
497 for i in range(len(filenameList)):
498 print "%s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
498 print "%s -> [%s]" %(filenameList[i], datetimeList[i].ctime())
499
499
500 self.filenameList = filenameList
500 self.filenameList = filenameList
501 self.datetimeList = datetimeList
501 self.datetimeList = datetimeList
502
502
503 return pathList, filenameList
503 return pathList, filenameList
504
504
505 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
505 def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None):
506
506
507 """
507 """
508 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
508 Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y
509 devuelve el archivo encontrado ademas de otros datos.
509 devuelve el archivo encontrado ademas de otros datos.
510
510
511 Input:
511 Input:
512 path : carpeta donde estan contenidos los files que contiene data
512 path : carpeta donde estan contenidos los files que contiene data
513
513
514 expLabel : Nombre del subexperimento (subfolder)
514 expLabel : Nombre del subexperimento (subfolder)
515
515
516 ext : extension de los files
516 ext : extension de los files
517
517
518 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
518 walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath)
519
519
520 Return:
520 Return:
521 directory : eL directorio donde esta el file encontrado
521 directory : eL directorio donde esta el file encontrado
522 filename : el ultimo file de una determinada carpeta
522 filename : el ultimo file de una determinada carpeta
523 year : el anho
523 year : el anho
524 doy : el numero de dia del anho
524 doy : el numero de dia del anho
525 set : el set del archivo
525 set : el set del archivo
526
526
527
527
528 """
528 """
529 dirList = []
529 dirList = []
530
530
531 if not walk:
531 if not walk:
532 fullpath = path
532 fullpath = path
533 foldercounter = 0
533 foldercounter = 0
534 else:
534 else:
535 #Filtra solo los directorios
535 #Filtra solo los directorios
536 for thisPath in os.listdir(path):
536 for thisPath in os.listdir(path):
537 if not os.path.isdir(os.path.join(path,thisPath)):
537 if not os.path.isdir(os.path.join(path,thisPath)):
538 continue
538 continue
539 if not isDoyFolder(thisPath):
539 if not isDoyFolder(thisPath):
540 continue
540 continue
541
541
542 dirList.append(thisPath)
542 dirList.append(thisPath)
543
543
544 if not(dirList):
544 if not(dirList):
545 return None, None, None, None, None, None
545 return None, None, None, None, None, None
546
546
547 dirList = sorted( dirList, key=str.lower )
547 dirList = sorted( dirList, key=str.lower )
548
548
549 doypath = dirList[-1]
549 doypath = dirList[-1]
550 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
550 foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0
551 fullpath = os.path.join(path, doypath, expLabel)
551 fullpath = os.path.join(path, doypath, expLabel)
552
552
553
553
554 print "%s folder was found: " %(fullpath )
554 print "%s folder was found: " %(fullpath )
555
555
556 if set == None:
556 if set == None:
557 filename = getlastFileFromPath(fullpath, ext)
557 filename = getlastFileFromPath(fullpath, ext)
558 else:
558 else:
559 filename = getFileFromSet(fullpath, ext, set)
559 filename = getFileFromSet(fullpath, ext, set)
560
560
561 if not(filename):
561 if not(filename):
562 return None, None, None, None, None, None
562 return None, None, None, None, None, None
563
563
564 print "%s file was found" %(filename)
564 print "%s file was found" %(filename)
565
565
566 if not(self.__verifyFile(os.path.join(fullpath, filename))):
566 if not(self.__verifyFile(os.path.join(fullpath, filename))):
567 return None, None, None, None, None, None
567 return None, None, None, None, None, None
568
568
569 year = int( filename[1:5] )
569 year = int( filename[1:5] )
570 doy = int( filename[5:8] )
570 doy = int( filename[5:8] )
571 set = int( filename[8:11] )
571 set = int( filename[8:11] )
572
572
573 return fullpath, foldercounter, filename, year, doy, set
573 return fullpath, foldercounter, filename, year, doy, set
574
574
575 def __setNextFileOffline(self):
575 def __setNextFileOffline(self):
576
576
577 idFile = self.fileIndex
577 idFile = self.fileIndex
578
578
579 while (True):
579 while (True):
580 idFile += 1
580 idFile += 1
581 if not(idFile < len(self.filenameList)):
581 if not(idFile < len(self.filenameList)):
582 self.flagNoMoreFiles = 1
582 self.flagNoMoreFiles = 1
583 print "No more Files"
583 print "No more Files"
584 return 0
584 return 0
585
585
586 filename = self.filenameList[idFile]
586 filename = self.filenameList[idFile]
587
587
588 if not(self.__verifyFile(filename)):
588 if not(self.__verifyFile(filename)):
589 continue
589 continue
590
590
591 fileSize = os.path.getsize(filename)
591 fileSize = os.path.getsize(filename)
592 fp = open(filename,'rb')
592 fp = open(filename,'rb')
593 break
593 break
594
594
595 self.flagIsNewFile = 1
595 self.flagIsNewFile = 1
596 self.fileIndex = idFile
596 self.fileIndex = idFile
597 self.filename = filename
597 self.filename = filename
598 self.fileSize = fileSize
598 self.fileSize = fileSize
599 self.fp = fp
599 self.fp = fp
600
600
601 print "Setting the file: %s"%self.filename
601 print "[Reading] Setting the file: %s"%self.filename
602
602
603 return 1
603 return 1
604
604
605 def __setNextFileOnline(self):
605 def __setNextFileOnline(self):
606 """
606 """
607 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
607 Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si
608 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
608 no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files
609 siguientes.
609 siguientes.
610
610
611 Affected:
611 Affected:
612 self.flagIsNewFile
612 self.flagIsNewFile
613 self.filename
613 self.filename
614 self.fileSize
614 self.fileSize
615 self.fp
615 self.fp
616 self.set
616 self.set
617 self.flagNoMoreFiles
617 self.flagNoMoreFiles
618
618
619 Return:
619 Return:
620 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
620 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado
621 1 : si el file fue abierto con exito y esta listo a ser leido
621 1 : si el file fue abierto con exito y esta listo a ser leido
622
622
623 Excepciones:
623 Excepciones:
624 Si un determinado file no puede ser abierto
624 Si un determinado file no puede ser abierto
625 """
625 """
626 nFiles = 0
626 nFiles = 0
627 fileOk_flag = False
627 fileOk_flag = False
628 firstTime_flag = True
628 firstTime_flag = True
629
629
630 self.set += 1
630 self.set += 1
631
631
632 if self.set > 999:
632 if self.set > 999:
633 self.set = 0
633 self.set = 0
634 self.foldercounter += 1
634 self.foldercounter += 1
635
635
636 #busca el 1er file disponible
636 #busca el 1er file disponible
637 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
637 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
638 if fullfilename:
638 if fullfilename:
639 if self.__verifyFile(fullfilename, False):
639 if self.__verifyFile(fullfilename, False):
640 fileOk_flag = True
640 fileOk_flag = True
641
641
642 #si no encuentra un file entonces espera y vuelve a buscar
642 #si no encuentra un file entonces espera y vuelve a buscar
643 if not(fileOk_flag):
643 if not(fileOk_flag):
644 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
644 for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles
645
645
646 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
646 if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces
647 tries = self.nTries
647 tries = self.nTries
648 else:
648 else:
649 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
649 tries = 1 #si no es la 1era vez entonces solo lo hace una vez
650
650
651 for nTries in range( tries ):
651 for nTries in range( tries ):
652 if firstTime_flag:
652 if firstTime_flag:
653 print "\tWaiting %0.2f sec for the file \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
653 print "\tWaiting %0.2f sec for the file \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 )
654 sleep( self.delay )
654 sleep( self.delay )
655 else:
655 else:
656 print "\tSearching next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
656 print "\tSearching next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext)
657
657
658 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
658 fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext )
659 if fullfilename:
659 if fullfilename:
660 if self.__verifyFile(fullfilename):
660 if self.__verifyFile(fullfilename):
661 fileOk_flag = True
661 fileOk_flag = True
662 break
662 break
663
663
664 if fileOk_flag:
664 if fileOk_flag:
665 break
665 break
666
666
667 firstTime_flag = False
667 firstTime_flag = False
668
668
669 print "\tSkipping the file \"%s\" due to this file doesn't exist" % filename
669 print "\tSkipping the file \"%s\" due to this file doesn't exist" % filename
670 self.set += 1
670 self.set += 1
671
671
672 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
672 if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta
673 self.set = 0
673 self.set = 0
674 self.doy += 1
674 self.doy += 1
675 self.foldercounter = 0
675 self.foldercounter = 0
676
676
677 if fileOk_flag:
677 if fileOk_flag:
678 self.fileSize = os.path.getsize( fullfilename )
678 self.fileSize = os.path.getsize( fullfilename )
679 self.filename = fullfilename
679 self.filename = fullfilename
680 self.flagIsNewFile = 1
680 self.flagIsNewFile = 1
681 if self.fp != None: self.fp.close()
681 if self.fp != None: self.fp.close()
682 self.fp = open(fullfilename, 'rb')
682 self.fp = open(fullfilename, 'rb')
683 self.flagNoMoreFiles = 0
683 self.flagNoMoreFiles = 0
684 print 'Setting the file: %s' % fullfilename
684 print '[Reading] Setting the file: %s' % fullfilename
685 else:
685 else:
686 self.fileSize = 0
686 self.fileSize = 0
687 self.filename = None
687 self.filename = None
688 self.flagIsNewFile = 0
688 self.flagIsNewFile = 0
689 self.fp = None
689 self.fp = None
690 self.flagNoMoreFiles = 1
690 self.flagNoMoreFiles = 1
691 print 'No more Files'
691 print '[Reading] No more files to read'
692
692
693 return fileOk_flag
693 return fileOk_flag
694
694
695 def setNextFile(self):
695 def setNextFile(self):
696 if self.fp != None:
696 if self.fp != None:
697 self.fp.close()
697 self.fp.close()
698
698
699 if self.online:
699 if self.online:
700 newFile = self.__setNextFileOnline()
700 newFile = self.__setNextFileOnline()
701 else:
701 else:
702 newFile = self.__setNextFileOffline()
702 newFile = self.__setNextFileOffline()
703
703
704 if not(newFile):
704 if not(newFile):
705 return 0
705 return 0
706
706
707 self.__readFirstHeader()
707 self.__readFirstHeader()
708 self.nReadBlocks = 0
708 self.nReadBlocks = 0
709 return 1
709 return 1
710
710
711 def __waitNewBlock(self):
711 def __waitNewBlock(self):
712 """
712 """
713 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
713 Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma.
714
714
715 Si el modo de lectura es OffLine siempre retorn 0
715 Si el modo de lectura es OffLine siempre retorn 0
716 """
716 """
717 if not self.online:
717 if not self.online:
718 return 0
718 return 0
719
719
720 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
720 if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile):
721 return 0
721 return 0
722
722
723 currentPointer = self.fp.tell()
723 currentPointer = self.fp.tell()
724
724
725 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
725 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
726
726
727 for nTries in range( self.nTries ):
727 for nTries in range( self.nTries ):
728
728
729 self.fp.close()
729 self.fp.close()
730 self.fp = open( self.filename, 'rb' )
730 self.fp = open( self.filename, 'rb' )
731 self.fp.seek( currentPointer )
731 self.fp.seek( currentPointer )
732
732
733 self.fileSize = os.path.getsize( self.filename )
733 self.fileSize = os.path.getsize( self.filename )
734 currentSize = self.fileSize - currentPointer
734 currentSize = self.fileSize - currentPointer
735
735
736 if ( currentSize >= neededSize ):
736 if ( currentSize >= neededSize ):
737 self.basicHeaderObj.read(self.fp)
737 self.basicHeaderObj.read(self.fp)
738 return 1
738 return 1
739
739
740 if self.fileSize == self.fileSizeByHeader:
740 if self.fileSize == self.fileSizeByHeader:
741 # self.flagEoF = True
741 # self.flagEoF = True
742 return 0
742 return 0
743
743
744 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
744 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
745 sleep( self.delay )
745 sleep( self.delay )
746
746
747
747
748 return 0
748 return 0
749
749
750 def waitDataBlock(self,pointer_location):
750 def waitDataBlock(self,pointer_location):
751
751
752 currentPointer = pointer_location
752 currentPointer = pointer_location
753
753
754 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
754 neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize
755
755
756 for nTries in range( self.nTries ):
756 for nTries in range( self.nTries ):
757 self.fp.close()
757 self.fp.close()
758 self.fp = open( self.filename, 'rb' )
758 self.fp = open( self.filename, 'rb' )
759 self.fp.seek( currentPointer )
759 self.fp.seek( currentPointer )
760
760
761 self.fileSize = os.path.getsize( self.filename )
761 self.fileSize = os.path.getsize( self.filename )
762 currentSize = self.fileSize - currentPointer
762 currentSize = self.fileSize - currentPointer
763
763
764 if ( currentSize >= neededSize ):
764 if ( currentSize >= neededSize ):
765 return 1
765 return 1
766
766
767 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
767 print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1)
768 sleep( self.delay )
768 sleep( self.delay )
769
769
770 return 0
770 return 0
771
771
772 def __jumpToLastBlock(self):
772 def __jumpToLastBlock(self):
773
773
774 if not(self.__isFirstTimeOnline):
774 if not(self.__isFirstTimeOnline):
775 return
775 return
776
776
777 csize = self.fileSize - self.fp.tell()
777 csize = self.fileSize - self.fp.tell()
778 blocksize = self.processingHeaderObj.blockSize
778 blocksize = self.processingHeaderObj.blockSize
779
779
780 #salta el primer bloque de datos
780 #salta el primer bloque de datos
781 if csize > self.processingHeaderObj.blockSize:
781 if csize > self.processingHeaderObj.blockSize:
782 self.fp.seek(self.fp.tell() + blocksize)
782 self.fp.seek(self.fp.tell() + blocksize)
783 else:
783 else:
784 return
784 return
785
785
786 csize = self.fileSize - self.fp.tell()
786 csize = self.fileSize - self.fp.tell()
787 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
787 neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
788 while True:
788 while True:
789
789
790 if self.fp.tell()<self.fileSize:
790 if self.fp.tell()<self.fileSize:
791 self.fp.seek(self.fp.tell() + neededsize)
791 self.fp.seek(self.fp.tell() + neededsize)
792 else:
792 else:
793 self.fp.seek(self.fp.tell() - neededsize)
793 self.fp.seek(self.fp.tell() - neededsize)
794 break
794 break
795
795
796 # csize = self.fileSize - self.fp.tell()
796 # csize = self.fileSize - self.fp.tell()
797 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
797 # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize
798 # factor = int(csize/neededsize)
798 # factor = int(csize/neededsize)
799 # if factor > 0:
799 # if factor > 0:
800 # self.fp.seek(self.fp.tell() + factor*neededsize)
800 # self.fp.seek(self.fp.tell() + factor*neededsize)
801
801
802 self.flagIsNewFile = 0
802 self.flagIsNewFile = 0
803 self.__isFirstTimeOnline = 0
803 self.__isFirstTimeOnline = 0
804
804
805 def __setNewBlock(self):
805 def __setNewBlock(self):
806
806
807 if self.fp == None:
807 if self.fp == None:
808 return 0
808 return 0
809
809
810 if self.online:
810 if self.online:
811 self.__jumpToLastBlock()
811 self.__jumpToLastBlock()
812
812
813 if self.flagIsNewFile:
813 if self.flagIsNewFile:
814 return 1
814 return 1
815
815
816 self.lastUTTime = self.basicHeaderObj.utc
816 self.lastUTTime = self.basicHeaderObj.utc
817 currentSize = self.fileSize - self.fp.tell()
817 currentSize = self.fileSize - self.fp.tell()
818 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
818 neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize
819
819
820 if (currentSize >= neededSize):
820 if (currentSize >= neededSize):
821 self.basicHeaderObj.read(self.fp)
821 self.basicHeaderObj.read(self.fp)
822 return 1
822 return 1
823
823
824 if self.__waitNewBlock():
824 if self.__waitNewBlock():
825 return 1
825 return 1
826
826
827 if not(self.setNextFile()):
827 if not(self.setNextFile()):
828 return 0
828 return 0
829
829
830 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
830 deltaTime = self.basicHeaderObj.utc - self.lastUTTime #
831
831
832 self.flagDiscontinuousBlock = 0
832 self.flagDiscontinuousBlock = 0
833
833
834 if deltaTime > self.maxTimeStep:
834 if deltaTime > self.maxTimeStep:
835 self.flagDiscontinuousBlock = 1
835 self.flagDiscontinuousBlock = 1
836
836
837 return 1
837 return 1
838
838
839 def readNextBlock(self):
839 def readNextBlock(self):
840 if not(self.__setNewBlock()):
840 if not(self.__setNewBlock()):
841 return 0
841 return 0
842
842
843 if not(self.readBlock()):
843 if not(self.readBlock()):
844 return 0
844 return 0
845
845
846 return 1
846 return 1
847
847
848 def __readFirstHeader(self):
848 def __readFirstHeader(self):
849
849
850 self.basicHeaderObj.read(self.fp)
850 self.basicHeaderObj.read(self.fp)
851 self.systemHeaderObj.read(self.fp)
851 self.systemHeaderObj.read(self.fp)
852 self.radarControllerHeaderObj.read(self.fp)
852 self.radarControllerHeaderObj.read(self.fp)
853 self.processingHeaderObj.read(self.fp)
853 self.processingHeaderObj.read(self.fp)
854
854
855 self.firstHeaderSize = self.basicHeaderObj.size
855 self.firstHeaderSize = self.basicHeaderObj.size
856
856
857 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
857 datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
858 if datatype == 0:
858 if datatype == 0:
859 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
859 datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')])
860 elif datatype == 1:
860 elif datatype == 1:
861 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
861 datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')])
862 elif datatype == 2:
862 elif datatype == 2:
863 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
863 datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')])
864 elif datatype == 3:
864 elif datatype == 3:
865 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
865 datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')])
866 elif datatype == 4:
866 elif datatype == 4:
867 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
867 datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')])
868 elif datatype == 5:
868 elif datatype == 5:
869 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
869 datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')])
870 else:
870 else:
871 raise ValueError, 'Data type was not defined'
871 raise ValueError, 'Data type was not defined'
872
872
873 self.dtype = datatype_str
873 self.dtype = datatype_str
874 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
874 #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c
875 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
875 self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1)
876 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
876 # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels)
877 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
877 # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels)
878 self.getBlockDimension()
878 self.getBlockDimension()
879
879
880 def __verifyFile(self, filename, msgFlag=True):
880 def __verifyFile(self, filename, msgFlag=True):
881 msg = None
881 msg = None
882 try:
882 try:
883 fp = open(filename, 'rb')
883 fp = open(filename, 'rb')
884 currentPosition = fp.tell()
884 currentPosition = fp.tell()
885 except IOError:
885 except IOError:
886 traceback.print_exc()
886 traceback.print_exc()
887 if msgFlag:
887 if msgFlag:
888 print "[Reading] The file %s can't be opened" % (filename)
888 print "[Reading] The file %s can't be opened" % (filename)
889 return False
889 return False
890
890
891 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
891 neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize
892
892
893 if neededSize == 0:
893 if neededSize == 0:
894 basicHeaderObj = BasicHeader(LOCALTIME)
894 basicHeaderObj = BasicHeader(LOCALTIME)
895 systemHeaderObj = SystemHeader()
895 systemHeaderObj = SystemHeader()
896 radarControllerHeaderObj = RadarControllerHeader()
896 radarControllerHeaderObj = RadarControllerHeader()
897 processingHeaderObj = ProcessingHeader()
897 processingHeaderObj = ProcessingHeader()
898
898
899 try:
899 try:
900 if not( basicHeaderObj.read(fp) ): raise IOError
900 if not( basicHeaderObj.read(fp) ): raise IOError
901 if not( systemHeaderObj.read(fp) ): raise IOError
901 if not( systemHeaderObj.read(fp) ): raise IOError
902 if not( radarControllerHeaderObj.read(fp) ): raise IOError
902 if not( radarControllerHeaderObj.read(fp) ): raise IOError
903 if not( processingHeaderObj.read(fp) ): raise IOError
903 if not( processingHeaderObj.read(fp) ): raise IOError
904 # data_type = int(numpy.log2((processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
904 # data_type = int(numpy.log2((processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR))
905
905
906 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
906 neededSize = processingHeaderObj.blockSize + basicHeaderObj.size
907
907
908 except IOError:
908 except IOError:
909 traceback.print_exc()
909 traceback.print_exc()
910 if msgFlag:
910 if msgFlag:
911 print "[Reading] The file %s is empty or it hasn't enough data" % filename
911 print "[Reading] The file %s is empty or it hasn't enough data" % filename
912
912
913 fp.close()
913 fp.close()
914 return False
914 return False
915 else:
915 else:
916 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
916 msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename
917
917
918 fp.close()
918 fp.close()
919 fileSize = os.path.getsize(filename)
919 fileSize = os.path.getsize(filename)
920 currentSize = fileSize - currentPosition
920 currentSize = fileSize - currentPosition
921 if currentSize < neededSize:
921 if currentSize < neededSize:
922 if msgFlag and (msg != None):
922 if msgFlag and (msg != None):
923 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
923 print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename
924 return False
924 return False
925
925
926 return True
926 return True
927
927
928 def setup(self,
928 def setup(self,
929 path=None,
929 path=None,
930 startDate=None,
930 startDate=None,
931 endDate=None,
931 endDate=None,
932 startTime=datetime.time(0,0,0),
932 startTime=datetime.time(0,0,0),
933 endTime=datetime.time(23,59,59),
933 endTime=datetime.time(23,59,59),
934 set=None,
934 set=None,
935 expLabel = "",
935 expLabel = "",
936 ext = None,
936 ext = None,
937 online = False,
937 online = False,
938 delay = 60,
938 delay = 60,
939 walk = True,
939 walk = True,
940 getblock = False,
940 getblock = False,
941 nTxs = 1):
941 nTxs = 1):
942
942
943 if path == None:
943 if path == None:
944 raise ValueError, "[Reading] The path is not valid"
944 raise ValueError, "[Reading] The path is not valid"
945
945
946 if ext == None:
946 if ext == None:
947 ext = self.ext
947 ext = self.ext
948
948
949 if online:
949 if online:
950 print "[Reading] Searching files in online mode..."
950 print "[Reading] Searching files in online mode..."
951
951
952 for nTries in range( self.nTries ):
952 for nTries in range( self.nTries ):
953 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
953 fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set)
954
954
955 if fullpath:
955 if fullpath:
956 break
956 break
957
957
958 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
958 print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1)
959 sleep( self.delay )
959 sleep( self.delay )
960
960
961 if not(fullpath):
961 if not(fullpath):
962 print "There 'isn't any valid file in %s" % path
962 print "[Reading] There 'isn't any valid file in %s" % path
963 return None
963 return None
964
964
965 self.year = year
965 self.year = year
966 self.doy = doy
966 self.doy = doy
967 self.set = set - 1
967 self.set = set - 1
968 self.path = path
968 self.path = path
969 self.foldercounter = foldercounter
969 self.foldercounter = foldercounter
970 last_set = None
970 last_set = None
971
971
972 else:
972 else:
973 print "[Reading] Searching files in offline mode ..."
973 print "[Reading] Searching files in offline mode ..."
974 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
974 pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate,
975 startTime=startTime, endTime=endTime,
975 startTime=startTime, endTime=endTime,
976 set=set, expLabel=expLabel, ext=ext,
976 set=set, expLabel=expLabel, ext=ext,
977 walk=walk)
977 walk=walk)
978
978
979 if not(pathList):
979 if not(pathList):
980 print "[Reading] No *%s files into the folder %s \nfor the range: %s - %s"%(ext, path,
980 print "[Reading] No *%s files into the folder %s \nfor the range: %s - %s"%(ext, path,
981 datetime.datetime.combine(startDate,startTime).ctime(),
981 datetime.datetime.combine(startDate,startTime).ctime(),
982 datetime.datetime.combine(endDate,endTime).ctime())
982 datetime.datetime.combine(endDate,endTime).ctime())
983
983
984 sys.exit(-1)
984 sys.exit(-1)
985
985
986
986
987 self.fileIndex = -1
987 self.fileIndex = -1
988 self.pathList = pathList
988 self.pathList = pathList
989 self.filenameList = filenameList
989 self.filenameList = filenameList
990 file_name = os.path.basename(filenameList[-1])
990 file_name = os.path.basename(filenameList[-1])
991 basename, ext = os.path.splitext(file_name)
991 basename, ext = os.path.splitext(file_name)
992 last_set = int(basename[-3:])
992 last_set = int(basename[-3:])
993
993
994 self.online = online
994 self.online = online
995 self.delay = delay
995 self.delay = delay
996 ext = ext.lower()
996 ext = ext.lower()
997 self.ext = ext
997 self.ext = ext
998 self.getByBlock = getblock
998 self.getByBlock = getblock
999 self.nTxs = int(nTxs)
999 self.nTxs = int(nTxs)
1000
1000
1001 if not(self.setNextFile()):
1001 if not(self.setNextFile()):
1002 if (startDate!=None) and (endDate!=None):
1002 if (startDate!=None) and (endDate!=None):
1003 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1003 print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime())
1004 elif startDate != None:
1004 elif startDate != None:
1005 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1005 print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime())
1006 else:
1006 else:
1007 print "[Reading] No files"
1007 print "[Reading] No files"
1008
1008
1009 sys.exit(-1)
1009 sys.exit(-1)
1010
1010
1011 # self.updateDataHeader()
1011 # self.updateDataHeader()
1012 if last_set != None:
1012 if last_set != None:
1013 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1013 self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock
1014 return
1014 return
1015
1015
1016 def getBasicHeader(self):
1016 def getBasicHeader(self):
1017
1017
1018 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1018 self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds
1019
1019
1020 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1020 self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock
1021
1021
1022 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1022 self.dataOut.timeZone = self.basicHeaderObj.timeZone
1023
1023
1024 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1024 self.dataOut.dstFlag = self.basicHeaderObj.dstFlag
1025
1025
1026 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1026 self.dataOut.errorCount = self.basicHeaderObj.errorCount
1027
1027
1028 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1028 self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime
1029
1029
1030 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1030 self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs
1031
1031
1032 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1032 self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs
1033
1033
1034
1034
1035 def getFirstHeader(self):
1035 def getFirstHeader(self):
1036
1036
1037 raise ValueError, "This method has not been implemented"
1037 raise ValueError, "This method has not been implemented"
1038
1038
1039 def getData(self):
1039 def getData(self):
1040
1040
1041 raise ValueError, "This method has not been implemented"
1041 raise ValueError, "This method has not been implemented"
1042
1042
1043 def hasNotDataInBuffer(self):
1043 def hasNotDataInBuffer(self):
1044
1044
1045 raise ValueError, "This method has not been implemented"
1045 raise ValueError, "This method has not been implemented"
1046
1046
1047 def readBlock(self):
1047 def readBlock(self):
1048
1048
1049 raise ValueError, "This method has not been implemented"
1049 raise ValueError, "This method has not been implemented"
1050
1050
1051 def isEndProcess(self):
1051 def isEndProcess(self):
1052
1052
1053 return self.flagNoMoreFiles
1053 return self.flagNoMoreFiles
1054
1054
1055 def printReadBlocks(self):
1055 def printReadBlocks(self):
1056
1056
1057 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1057 print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks
1058
1058
1059 def printTotalBlocks(self):
1059 def printTotalBlocks(self):
1060
1060
1061 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1061 print "[Reading] Number of read blocks %04d" %self.nTotalBlocks
1062
1062
1063 def printNumberOfBlock(self):
1063 def printNumberOfBlock(self):
1064
1064
1065 if self.flagIsNewBlock:
1065 if self.flagIsNewBlock:
1066 print "[Reading] Block No. %04d, Total blocks %04d -> %s" %(self.basicHeaderObj.dataBlock, self.nTotalBlocks, self.dataOut.datatime.ctime())
1066 print "[Reading] Block No. %04d, Total blocks %04d -> %s" %(self.basicHeaderObj.dataBlock, self.nTotalBlocks, self.dataOut.datatime.ctime())
1067 self.dataOut.blocknow = self.basicHeaderObj.dataBlock
1067 self.dataOut.blocknow = self.basicHeaderObj.dataBlock
1068
1068
1069 def printInfo(self):
1069 def printInfo(self):
1070
1070
1071 if self.__printInfo == False:
1071 if self.__printInfo == False:
1072 return
1072 return
1073
1073
1074 self.basicHeaderObj.printInfo()
1074 self.basicHeaderObj.printInfo()
1075 self.systemHeaderObj.printInfo()
1075 self.systemHeaderObj.printInfo()
1076 self.radarControllerHeaderObj.printInfo()
1076 self.radarControllerHeaderObj.printInfo()
1077 self.processingHeaderObj.printInfo()
1077 self.processingHeaderObj.printInfo()
1078
1078
1079 self.__printInfo = False
1079 self.__printInfo = False
1080
1080
1081
1081
1082 def run(self, **kwargs):
1082 def run(self, **kwargs):
1083
1083
1084 if not(self.isConfig):
1084 if not(self.isConfig):
1085
1085
1086 # self.dataOut = dataOut
1086 # self.dataOut = dataOut
1087 self.setup(**kwargs)
1087 self.setup(**kwargs)
1088 self.isConfig = True
1088 self.isConfig = True
1089
1089
1090 self.getData()
1090 self.getData()
1091
1091
1092 class JRODataWriter(JRODataIO):
1092 class JRODataWriter(JRODataIO):
1093
1093
1094 """
1094 """
1095 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1095 Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura
1096 de los datos siempre se realiza por bloques.
1096 de los datos siempre se realiza por bloques.
1097 """
1097 """
1098
1098
1099 blockIndex = 0
1099 blockIndex = 0
1100
1100
1101 path = None
1101 path = None
1102
1102
1103 setFile = None
1103 setFile = None
1104
1104
1105 profilesPerBlock = None
1105 profilesPerBlock = None
1106
1106
1107 blocksPerFile = None
1107 blocksPerFile = None
1108
1108
1109 nWriteBlocks = 0
1109 nWriteBlocks = 0
1110
1110
1111 def __init__(self, dataOut=None):
1111 def __init__(self, dataOut=None):
1112 raise ValueError, "Not implemented"
1112 raise ValueError, "Not implemented"
1113
1113
1114
1114
1115 def hasAllDataInBuffer(self):
1115 def hasAllDataInBuffer(self):
1116 raise ValueError, "Not implemented"
1116 raise ValueError, "Not implemented"
1117
1117
1118
1118
1119 def setBlockDimension(self):
1119 def setBlockDimension(self):
1120 raise ValueError, "Not implemented"
1120 raise ValueError, "Not implemented"
1121
1121
1122
1122
1123 def writeBlock(self):
1123 def writeBlock(self):
1124 raise ValueError, "No implemented"
1124 raise ValueError, "No implemented"
1125
1125
1126
1126
1127 def putData(self):
1127 def putData(self):
1128 raise ValueError, "No implemented"
1128 raise ValueError, "No implemented"
1129
1129
1130
1130
1131 def setBasicHeader(self):
1131 def setBasicHeader(self):
1132
1132
1133 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1133 self.basicHeaderObj.size = self.basicHeaderSize #bytes
1134 self.basicHeaderObj.version = self.versionFile
1134 self.basicHeaderObj.version = self.versionFile
1135 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1135 self.basicHeaderObj.dataBlock = self.nTotalBlocks
1136
1136
1137 utc = numpy.floor(self.dataOut.utctime)
1137 utc = numpy.floor(self.dataOut.utctime)
1138 milisecond = (self.dataOut.utctime - utc)* 1000.0
1138 milisecond = (self.dataOut.utctime - utc)* 1000.0
1139
1139
1140 self.basicHeaderObj.utc = utc
1140 self.basicHeaderObj.utc = utc
1141 self.basicHeaderObj.miliSecond = milisecond
1141 self.basicHeaderObj.miliSecond = milisecond
1142 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1142 self.basicHeaderObj.timeZone = self.dataOut.timeZone
1143 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1143 self.basicHeaderObj.dstFlag = self.dataOut.dstFlag
1144 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1144 self.basicHeaderObj.errorCount = self.dataOut.errorCount
1145
1145
1146 def setFirstHeader(self):
1146 def setFirstHeader(self):
1147 """
1147 """
1148 Obtiene una copia del First Header
1148 Obtiene una copia del First Header
1149
1149
1150 Affected:
1150 Affected:
1151
1151
1152 self.basicHeaderObj
1152 self.basicHeaderObj
1153 self.systemHeaderObj
1153 self.systemHeaderObj
1154 self.radarControllerHeaderObj
1154 self.radarControllerHeaderObj
1155 self.processingHeaderObj self.
1155 self.processingHeaderObj self.
1156
1156
1157 Return:
1157 Return:
1158 None
1158 None
1159 """
1159 """
1160
1160
1161 raise ValueError, "No implemented"
1161 raise ValueError, "No implemented"
1162
1162
1163 def __writeFirstHeader(self):
1163 def __writeFirstHeader(self):
1164 """
1164 """
1165 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1165 Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader)
1166
1166
1167 Affected:
1167 Affected:
1168 __dataType
1168 __dataType
1169
1169
1170 Return:
1170 Return:
1171 None
1171 None
1172 """
1172 """
1173
1173
1174 # CALCULAR PARAMETROS
1174 # CALCULAR PARAMETROS
1175
1175
1176 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1176 sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size
1177 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1177 self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader
1178
1178
1179 self.basicHeaderObj.write(self.fp)
1179 self.basicHeaderObj.write(self.fp)
1180 self.systemHeaderObj.write(self.fp)
1180 self.systemHeaderObj.write(self.fp)
1181 self.radarControllerHeaderObj.write(self.fp)
1181 self.radarControllerHeaderObj.write(self.fp)
1182 self.processingHeaderObj.write(self.fp)
1182 self.processingHeaderObj.write(self.fp)
1183
1183
1184 self.dtype = self.dataOut.dtype
1184 self.dtype = self.dataOut.dtype
1185
1185
1186 def __setNewBlock(self):
1186 def __setNewBlock(self):
1187 """
1187 """
1188 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1188 Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header
1189
1189
1190 Return:
1190 Return:
1191 0 : si no pudo escribir nada
1191 0 : si no pudo escribir nada
1192 1 : Si escribio el Basic el First Header
1192 1 : Si escribio el Basic el First Header
1193 """
1193 """
1194 if self.fp == None:
1194 if self.fp == None:
1195 self.setNextFile()
1195 self.setNextFile()
1196
1196
1197 if self.flagIsNewFile:
1197 if self.flagIsNewFile:
1198 return 1
1198 return 1
1199
1199
1200 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1200 if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile:
1201 self.basicHeaderObj.write(self.fp)
1201 self.basicHeaderObj.write(self.fp)
1202 return 1
1202 return 1
1203
1203
1204 if not( self.setNextFile() ):
1204 if not( self.setNextFile() ):
1205 return 0
1205 return 0
1206
1206
1207 return 1
1207 return 1
1208
1208
1209
1209
1210 def writeNextBlock(self):
1210 def writeNextBlock(self):
1211 """
1211 """
1212 Selecciona el bloque siguiente de datos y los escribe en un file
1212 Selecciona el bloque siguiente de datos y los escribe en un file
1213
1213
1214 Return:
1214 Return:
1215 0 : Si no hizo pudo escribir el bloque de datos
1215 0 : Si no hizo pudo escribir el bloque de datos
1216 1 : Si no pudo escribir el bloque de datos
1216 1 : Si no pudo escribir el bloque de datos
1217 """
1217 """
1218 if not( self.__setNewBlock() ):
1218 if not( self.__setNewBlock() ):
1219 return 0
1219 return 0
1220
1220
1221 self.writeBlock()
1221 self.writeBlock()
1222
1222
1223 return 1
1223 return 1
1224
1224
1225 def setNextFile(self):
1225 def setNextFile(self):
1226 """
1226 """
1227 Determina el siguiente file que sera escrito
1227 Determina el siguiente file que sera escrito
1228
1228
1229 Affected:
1229 Affected:
1230 self.filename
1230 self.filename
1231 self.subfolder
1231 self.subfolder
1232 self.fp
1232 self.fp
1233 self.setFile
1233 self.setFile
1234 self.flagIsNewFile
1234 self.flagIsNewFile
1235
1235
1236 Return:
1236 Return:
1237 0 : Si el archivo no puede ser escrito
1237 0 : Si el archivo no puede ser escrito
1238 1 : Si el archivo esta listo para ser escrito
1238 1 : Si el archivo esta listo para ser escrito
1239 """
1239 """
1240 ext = self.ext
1240 ext = self.ext
1241 path = self.path
1241 path = self.path
1242
1242
1243 if self.fp != None:
1243 if self.fp != None:
1244 self.fp.close()
1244 self.fp.close()
1245
1245
1246 timeTuple = time.localtime( self.dataOut.utctime)
1246 timeTuple = time.localtime( self.dataOut.utctime)
1247 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1247 subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday)
1248
1248
1249 fullpath = os.path.join( path, subfolder )
1249 fullpath = os.path.join( path, subfolder )
1250 if not( os.path.exists(fullpath) ):
1250 if not( os.path.exists(fullpath) ):
1251 os.mkdir(fullpath)
1251 os.mkdir(fullpath)
1252 self.setFile = -1 #inicializo mi contador de seteo
1252 self.setFile = -1 #inicializo mi contador de seteo
1253 else:
1253 else:
1254 filesList = os.listdir( fullpath )
1254 filesList = os.listdir( fullpath )
1255 if len( filesList ) > 0:
1255 if len( filesList ) > 0:
1256 filesList = sorted( filesList, key=str.lower )
1256 filesList = sorted( filesList, key=str.lower )
1257 filen = filesList[-1]
1257 filen = filesList[-1]
1258 # el filename debera tener el siguiente formato
1258 # el filename debera tener el siguiente formato
1259 # 0 1234 567 89A BCDE (hex)
1259 # 0 1234 567 89A BCDE (hex)
1260 # x YYYY DDD SSS .ext
1260 # x YYYY DDD SSS .ext
1261 if isNumber( filen[8:11] ):
1261 if isNumber( filen[8:11] ):
1262 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1262 self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file
1263 else:
1263 else:
1264 self.setFile = -1
1264 self.setFile = -1
1265 else:
1265 else:
1266 self.setFile = -1 #inicializo mi contador de seteo
1266 self.setFile = -1 #inicializo mi contador de seteo
1267
1267
1268 setFile = self.setFile
1268 setFile = self.setFile
1269 setFile += 1
1269 setFile += 1
1270
1270
1271 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1271 filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar,
1272 timeTuple.tm_year,
1272 timeTuple.tm_year,
1273 timeTuple.tm_yday,
1273 timeTuple.tm_yday,
1274 setFile,
1274 setFile,
1275 ext )
1275 ext )
1276
1276
1277 filename = os.path.join( path, subfolder, filen )
1277 filename = os.path.join( path, subfolder, filen )
1278
1278
1279 fp = open( filename,'wb' )
1279 fp = open( filename,'wb' )
1280
1280
1281 self.blockIndex = 0
1281 self.blockIndex = 0
1282
1282
1283 #guardando atributos
1283 #guardando atributos
1284 self.filename = filename
1284 self.filename = filename
1285 self.subfolder = subfolder
1285 self.subfolder = subfolder
1286 self.fp = fp
1286 self.fp = fp
1287 self.setFile = setFile
1287 self.setFile = setFile
1288 self.flagIsNewFile = 1
1288 self.flagIsNewFile = 1
1289
1289
1290 self.setFirstHeader()
1290 self.setFirstHeader()
1291
1291
1292 print '[Writing] file: %s'%self.filename
1292 print '[Writing] file: %s'%self.filename
1293
1293
1294 self.__writeFirstHeader()
1294 self.__writeFirstHeader()
1295
1295
1296 return 1
1296 return 1
1297
1297
1298 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=0, ext=None):
1298 def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=0, ext=None):
1299 """
1299 """
1300 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1300 Setea el tipo de formato en la cual sera guardada la data y escribe el First Header
1301
1301
1302 Inputs:
1302 Inputs:
1303 path : el path destino en el cual se escribiran los files a crear
1303 path : el path destino en el cual se escribiran los files a crear
1304 format : formato en el cual sera salvado un file
1304 format : formato en el cual sera salvado un file
1305 set : el setebo del file
1305 set : el setebo del file
1306
1306
1307 Return:
1307 Return:
1308 0 : Si no realizo un buen seteo
1308 0 : Si no realizo un buen seteo
1309 1 : Si realizo un buen seteo
1309 1 : Si realizo un buen seteo
1310 """
1310 """
1311
1311
1312 if ext == None:
1312 if ext == None:
1313 ext = self.ext
1313 ext = self.ext
1314
1314
1315 ext = ext.lower()
1315 ext = ext.lower()
1316
1316
1317 self.ext = ext
1317 self.ext = ext
1318
1318
1319 self.path = path
1319 self.path = path
1320
1320
1321 self.setFile = set - 1
1321 self.setFile = set - 1
1322
1322
1323 self.blocksPerFile = blocksPerFile
1323 self.blocksPerFile = blocksPerFile
1324
1324
1325 self.profilesPerBlock = profilesPerBlock
1325 self.profilesPerBlock = profilesPerBlock
1326
1326
1327 self.dataOut = dataOut
1327 self.dataOut = dataOut
1328
1328
1329 if not(self.setNextFile()):
1329 if not(self.setNextFile()):
1330 print "[Writing] There isn't a next file"
1330 print "[Writing] There isn't a next file"
1331 return 0
1331 return 0
1332
1332
1333 self.setBlockDimension()
1333 self.setBlockDimension()
1334
1334
1335 return 1
1335 return 1
1336
1336
1337 def run(self, dataOut, **kwargs):
1337 def run(self, dataOut, **kwargs):
1338
1338
1339 if not(self.isConfig):
1339 if not(self.isConfig):
1340
1340
1341 self.setup(dataOut, **kwargs)
1341 self.setup(dataOut, **kwargs)
1342 self.isConfig = True
1342 self.isConfig = True
1343
1343
1344 self.putData()
1344 self.putData()
1345
1345
@@ -1,135 +1,135
1 '''
1 '''
2 Created on Jul 15, 2014
2 Created on Jul 15, 2014
3
3
4 @author: roj-idl71
4 @author: roj-idl71
5 '''
5 '''
6 import time
6 import time
7 import threading
7 import threading
8 import cPickle
8 import cPickle
9
9
10 try:
10 try:
11 from gevent import sleep
11 from gevent import sleep
12 except:
12 except:
13 from time import sleep
13 from time import sleep
14
14
15 SERIALIZER = cPickle
15 SERIALIZER = cPickle
16
16
17 # from schainpy.serializer import DynamicSerializer
17 # from schainpy.serializer import DynamicSerializer
18 from schainpy.model.io.jroIO_usrp import USRPReader
18 from schainpy.model.io.jroIO_usrp import USRPReader
19 from schainpy.serializer.DataTranslate import obj2Serial
19 from schainpy.serializer.DataTranslate import obj2Serial
20
20
21 class USRPReaderAPI(USRPReader, threading.Thread):
21 class USRPReaderAPI(USRPReader, threading.Thread):
22
22
23 # __isBufferEmpty = True
23 # __isBufferEmpty = True
24
24
25 __DATAKEYLIST = ['data','utctime','flagNoData']
25 __DATAKEYLIST = ['data','utctime','flagNoData']
26
26
27 def __init__(self, serializer='msgpack'):
27 def __init__(self, serializer='msgpack'):
28
28
29 threading.Thread.__init__(self)
29 threading.Thread.__init__(self)
30 USRPReader.__init__(self)
30 USRPReader.__init__(self)
31
31
32 # self.__serializerObj = DynamicSerializer.DynamicSerializer('msgpack')
32 # self.__serializerObj = DynamicSerializer.DynamicSerializer('msgpack')
33 self.__mySerial = None
33 self.__mySerial = None
34 self.__isBufferEmpty = True
34 self.__isBufferEmpty = True
35
35
36 self.setSerializer(serializer)
36 self.setSerializer(serializer)
37
37
38 def setSerializer(self, serializer):
38 def setSerializer(self, serializer):
39
39
40 self.__serializer = serializer
40 self.__serializer = serializer
41
41
42 def getSerializer(self):
42 def getSerializer(self):
43
43
44 return self.__serializer
44 return self.__serializer
45
45
46 def getProfileIndex(self):
46 def getProfileIndex(self):
47
47
48 return self.profileIndex
48 return self.profileIndex
49
49
50 def getSerialMetaData(self):
50 def getSerialMetaData(self):
51
51
52 if self.__isBufferEmpty:
52 if self.__isBufferEmpty:
53 ini = time.time()
53 ini = time.time()
54
54
55 while True:
55 while True:
56
56
57 if not self.__isBufferEmpty:
57 if not self.__isBufferEmpty:
58 break
58 break
59
59
60 if time.time() - ini > 20:
60 if time.time() - ini > 20:
61 break
61 break
62
62
63 sleep(1e-12)
63 sleep(1e-12)
64
64
65
65
66 # if not self.getData():
66 # if not self.getData():
67 # self.__isBufferEmpty = False
67 # self.__isBufferEmpty = False
68 # return None
68 # return None
69
69
70 if self.dataOut.flagNoData:
70 if self.dataOut.flagNoData:
71 return None
71 return None
72
72
73 myMetadataSerial = obj2Serial(self.dataOut,
73 myMetadataSerial = obj2Serial(self.dataOut,
74 serializer = self.__serializer)
74 serializer = self.__serializer)
75
75
76 return myMetadataSerial
76 return myMetadataSerial
77
77
78 def getSerialData(self):
78 def getSerialData(self):
79
79
80 if self.__isBufferEmpty:
80 if self.__isBufferEmpty:
81 ini = time.time()
81 ini = time.time()
82
82
83 while True:
83 while True:
84
84
85 if not self.__isBufferEmpty:
85 if not self.__isBufferEmpty:
86 break
86 break
87
87
88 if time.time() - ini > 20:
88 if time.time() - ini > 20:
89 break
89 break
90
90
91 sleep(1e-12)
91 sleep(1e-12)
92
92
93
93
94 # if not self.getData():
94 # if not self.getData():
95 # self.__isBufferEmpty = False
95 # self.__isBufferEmpty = False
96 # return None
96 # return None
97
97
98 if self.dataOut.flagNoData:
98 if self.dataOut.flagNoData:
99 return None
99 return None
100
100
101 self.__isBufferEmpty = True
101 self.__isBufferEmpty = True
102
102
103 return self.__mySerial
103 return self.__mySerial
104
104
105 def run(self):
105 def run(self):
106
106
107 '''
107 '''
108 This method will be called many times so here you should put all your code
108 This method will be called once when start() is called
109 '''
109 '''
110
110
111 if not self.isConfig:
111 if not self.isConfig:
112 raise IOError, 'setup() method has to be called before start()'
112 raise IOError, 'setup() method has to be called before start()'
113
113
114 while True:
114 while True:
115
115
116 if not self.__isBufferEmpty:
116 if not self.__isBufferEmpty:
117 sleep(1e-12)
117 sleep(1e-12)
118 continue
118 continue
119
119
120 if not self.getData():
120 if not self.getData():
121 break
121 break
122
122
123 print ".",
123 print ".",
124
124
125 self.__mySerial = obj2Serial(self.dataOut,
125 self.__mySerial = obj2Serial(self.dataOut,
126 keyList = self.__DATAKEYLIST,
126 keyList = self.__DATAKEYLIST,
127 serializer = self.__serializer)
127 serializer = self.__serializer)
128 self.__isBufferEmpty = False
128 self.__isBufferEmpty = False
129
129
130 # print self.profileIndex
130 # print self.profileIndex
131 # print 'wait 1 second'
131 # print 'wait 1 second'
132
132
133 # sleep(0.1)
133 # sleep(0.1)
134
134
135 return No newline at end of file
135 return
@@ -1,268 +1,275
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):
30 def __init__(self):
31
31
32 self.dataIn = None
32 self.dataIn = None
33 self.dataInList = []
33 self.dataInList = []
34
34
35 self.dataOut = {}
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 def addOperation(self, opObj, objId):
41 def addOperation(self, opObj, objId):
42
42
43 """
43 """
44 Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el
44 Agrega un objeto del tipo "Operation" (opObj) a la lista de objetos "self.objectList" y retorna el
45 identificador asociado a este objeto.
45 identificador asociado a este objeto.
46
46
47 Input:
47 Input:
48
48
49 object : objeto de la clase "Operation"
49 object : objeto de la clase "Operation"
50
50
51 Return:
51 Return:
52
52
53 objId : identificador del objeto, necesario para ejecutar la operacion
53 objId : identificador del objeto, necesario para ejecutar la operacion
54 """
54 """
55
55
56 self.operations2RunDict[objId] = opObj
56 self.operations2RunDict[objId] = opObj
57
57
58 return objId
58 return objId
59
59
60 def operation(self, **kwargs):
60 def operation(self, **kwargs):
61
61
62 """
62 """
63 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
63 Operacion directa sobre la data (dataOut.data). Es necesario actualizar los valores de los
64 atributos del objeto dataOut
64 atributos del objeto dataOut
65
65
66 Input:
66 Input:
67
67
68 **kwargs : Diccionario de argumentos de la funcion a ejecutar
68 **kwargs : Diccionario de argumentos de la funcion a ejecutar
69 """
69 """
70
70
71 raise ValueError, "ImplementedError"
71 raise ValueError, "ImplementedError"
72
72
73 def callMethod(self, name, **kwargs):
73 def callMethod(self, name, **kwargs):
74
74
75 """
75 """
76 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
76 Ejecuta el metodo con el nombre "name" y con argumentos **kwargs de la propia clase.
77
77
78 Input:
78 Input:
79 name : nombre del metodo a ejecutar
79 name : nombre del metodo a ejecutar
80
80
81 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
81 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
82
82
83 """
83 """
84
84
85 #Checking the inputs
85 #Checking the inputs
86 if name == 'run':
86 if name == 'run':
87
87
88 if not self.checkInputs():
88 if not self.checkInputs():
89 self.dataOut.flagNoData = True
89 self.dataOut.flagNoData = True
90 return False
90 return False
91 else:
91 else:
92 #Si no es un metodo RUN la entrada es la misma dataOut (interna)
92 #Si no es un metodo RUN la entrada es la misma dataOut (interna)
93 if self.dataOut.isEmpty():
93 if self.dataOut.isEmpty():
94 return False
94 return False
95
95
96 #Getting the pointer to method
96 #Getting the pointer to method
97 methodToCall = getattr(self, name)
97 methodToCall = getattr(self, name)
98
98
99 #Executing the self method
99 #Executing the self method
100 methodToCall(**kwargs)
100 methodToCall(**kwargs)
101
101
102 #Checkin the outputs
102 #Checkin the outputs
103
103
104 # if name == 'run':
104 # if name == 'run':
105 # pass
105 # pass
106 # else:
106 # else:
107 # pass
107 # pass
108 #
108 #
109 # if name != 'run':
109 # if name != 'run':
110 # return True
110 # return True
111
111
112 if self.dataOut == None:
113 return False
114
112 if self.dataOut.isEmpty():
115 if self.dataOut.isEmpty():
113 return False
116 return False
114
117
115 return True
118 return True
116
119
117 def callObject(self, objId, **kwargs):
120 def callObject(self, objId, **kwargs):
118
121
119 """
122 """
120 Ejecuta la operacion asociada al identificador del objeto "objId"
123 Ejecuta la operacion asociada al identificador del objeto "objId"
121
124
122 Input:
125 Input:
123
126
124 objId : identificador del objeto a ejecutar
127 objId : identificador del objeto a ejecutar
125
128
126 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
129 **kwargs : diccionario con los nombres y valores de la funcion a ejecutar.
127
130
128 Return:
131 Return:
129
132
130 None
133 None
131 """
134 """
132
135
133 if self.dataOut.isEmpty():
136 if self.dataOut.isEmpty():
134 return False
137 return False
135
138
136 externalProcObj = self.operations2RunDict[objId]
139 externalProcObj = self.operations2RunDict[objId]
137
140
138 externalProcObj.run(self.dataOut, **kwargs)
141 externalProcObj.run(self.dataOut, **kwargs)
139
142
140 return True
143 return True
141
144
142 def call(self, opType, opName=None, opId=None, **kwargs):
145 def call(self, opType, opName=None, opId=None, **kwargs):
143
146
144 """
147 """
145 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
148 Return True si ejecuta la operacion interna nombrada "opName" o la operacion externa
146 identificada con el id "opId"; con los argumentos "**kwargs".
149 identificada con el id "opId"; con los argumentos "**kwargs".
147
150
148 False si la operacion no se ha ejecutado.
151 False si la operacion no se ha ejecutado.
149
152
150 Input:
153 Input:
151
154
152 opType : Puede ser "self" o "external"
155 opType : Puede ser "self" o "external"
153
156
154 La operacion puede ser de dos tipos (callMethod or callObject):
157 La operacion puede ser de dos tipos (callMethod or callObject):
155
158
156 1. Un metodo propio de esta clase:
159 1. Un metodo propio de esta clase:
157
160
158 opType = "self"
161 opType = "self"
159
162
160 2. El metodo "run" de un objeto del tipo Operation o de un derivado de ella:
163 2. El metodo "run" de un objeto del tipo Operation o de un derivado de ella:
161
164
162 opType = "other" or "external".
165 opType = "other" or "external".
163
166
164 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
167 opName : Si la operacion es interna (opType = 'self'), entonces el "opName" sera
165 usada para llamar a un metodo interno de la clase Processing
168 usada para llamar a un metodo interno de la clase Processing
166
169
167 opId : Si la operacion es externa (opType = 'other'), entonces el "opId" sera
170 opId : Si la operacion es externa (opType = 'other'), entonces el "opId" sera
168 usada para llamar al metodo "run" de la clase Operation registrada con ese Id
171 usada para llamar al metodo "run" de la clase Operation registrada con ese Id
169
172
170 Exception:
173 Exception:
171 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
174 Este objeto de tipo Operation debe de haber sido agregado antes con el metodo:
172 "addOperation" e identificado con el valor "opId" = el id de la operacion.
175 "addOperation" e identificado con el valor "opId" = el id de la operacion.
173 De lo contrario retornara un error del tipo IOError
176 De lo contrario retornara un error del tipo IOError
174
177
175 """
178 """
176
179
177 if opType == 'self':
180 if opType == 'self':
178
181
179 if not opName:
182 if not opName:
180 raise IOError, "opName parameter should be defined"
183 raise IOError, "opName parameter should be defined"
181
184
182 sts = self.callMethod(opName, **kwargs)
185 sts = self.callMethod(opName, **kwargs)
183
186
184 if opType == 'other' or opType == 'external':
187 if opType == 'other' or opType == 'external':
185
188
186 if not opId:
189 if not opId:
187 raise IOError, "opId parameter should be defined"
190 raise IOError, "opId parameter should be defined"
188
191
189 if opId not in self.operations2RunDict.keys():
192 if opId not in self.operations2RunDict.keys():
190 raise IOError, "This id operation have not been registered"
193 raise IOError, "This id operation have not been registered"
191
194
192 sts = self.callObject(opId, **kwargs)
195 sts = self.callObject(opId, **kwargs)
193
196
194 return sts
197 return sts
195
198
196 def setInput(self, dataIn):
199 def setInput(self, dataIn):
197
200
198 self.dataIn = dataIn
201 self.dataIn = dataIn
199 self.dataInList.append(dataIn)
202 self.dataInList.append(dataIn)
200
203
201 def getOutputObj(self):
204 def getOutputObj(self):
202
205
203 return self.dataOut
206 return self.dataOut
204
207
205 def checkInputs(self):
208 def checkInputs(self):
206
209
207 for thisDataIn in self.dataInList:
210 for thisDataIn in self.dataInList:
208
211
209 if thisDataIn.isEmpty():
212 if thisDataIn.isEmpty():
210 return False
213 return False
211
214
212 return True
215 return True
213
216
214 def setup(self):
217 def setup(self):
215
218
216 raise ValueError, "Not implemented"
219 raise ValueError, "Not implemented"
217
220
218 def run(self):
221 def run(self):
219
222
220 raise ValueError, "Not implemented"
223 raise ValueError, "Not implemented"
221
224
225 def close(self):
226 #Close every thread, queue or any other object here is it is neccesary.
227 return
228
222 class Operation(object):
229 class Operation(object):
223
230
224 """
231 """
225 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
232 Clase base para definir las operaciones adicionales que se pueden agregar a la clase ProcessingUnit
226 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
233 y necesiten acumular informacion previa de los datos a procesar. De preferencia usar un buffer de
227 acumulacion dentro de esta clase
234 acumulacion dentro de esta clase
228
235
229 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
236 Ejemplo: Integraciones coherentes, necesita la informacion previa de los n perfiles anteriores (bufffer)
230
237
231 """
238 """
232
239
233 __buffer = None
240 __buffer = None
234 isConfig = False
241 isConfig = False
235
242
236 def __init__(self):
243 def __init__(self):
237
244
238 self.__buffer = None
245 self.__buffer = None
239 self.isConfig = False
246 self.isConfig = False
240
247
241 def setup(self):
248 def setup(self):
242
249
243 self.isConfig = True
250 self.isConfig = True
244
251
245 raise ValueError, "Not implemented"
252 raise ValueError, "Not implemented"
246
253
247 def run(self, dataIn, **kwargs):
254 def run(self, dataIn, **kwargs):
248
255
249 """
256 """
250 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
257 Realiza las operaciones necesarias sobre la dataIn.data y actualiza los
251 atributos del objeto dataIn.
258 atributos del objeto dataIn.
252
259
253 Input:
260 Input:
254
261
255 dataIn : objeto del tipo JROData
262 dataIn : objeto del tipo JROData
256
263
257 Return:
264 Return:
258
265
259 None
266 None
260
267
261 Affected:
268 Affected:
262 __buffer : buffer de recepcion de datos.
269 __buffer : buffer de recepcion de datos.
263
270
264 """
271 """
265 if not self.isConfig:
272 if not self.isConfig:
266 self.setup(**kwargs)
273 self.setup(**kwargs)
267
274
268 raise ValueError, "ImplementedError" No newline at end of file
275 raise ValueError, "ImplementedError"
This diff has been collapsed as it changes many lines, (565 lines changed) Show them Hide them
@@ -1,353 +1,912
1 '''
1 '''
2 @author: Daniel Suarez
2 @author: Daniel Suarez
3 '''
3 '''
4 import os
4 import os
5 import glob
5 import glob
6 import ftplib
6 import ftplib
7
8 try:
9 import paramiko
10 import scp
11 except:
12 print "You should install paramiko if you will use SSH protocol to upload files to a server"
13
7 import multiprocessing
14 import multiprocessing
15
16 import time
17 import threading
18
19
20 try:
21 from gevent import sleep
22 except:
23 from time import sleep
24
8 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
25 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation
9
26
27 class Remote(threading.Thread):
28 """
29 Remote is a parent class used to define the behaviour of FTP and SSH class. These clases are
30 used to upload or download files remotely.
31
32 Non-standard Python modules used:
33 None
34
35 Written by:
36
37 "Miguel Urco":mailto:miguel.urco@jro.igp.gob.pe Jun. 03, 2015
38
39 """
40
41 server = None
42 username = None
43 password = None
44 remotefolder = None
45
46 period = 60
47 fileList = []
48 bussy = False
49
50 def __init__(self, server, username, password, remotefolder, period=60):
51
52 threading.Thread.__init__(self)
53 self._stop = threading.Event()
54
55 self.status = 0
56
57 self.period = period
58 self.fileList = []
59 self.bussy = False
60
61 self.stopFlag = False
62
63 print "[Remote Server] Opening server: %s" %server
64 if self.open(server, username, password, remotefolder):
65 print "[Remote Server] %s server was opened successfully" %server
66
67 def stop(self):
68
69 self.stopFlag = True
70
71 def open(self):
72 """
73 Connect to server and create a connection class (FTP or SSH) to remote server.
74 """
75 raise NotImplementedError, "Implement this method in child class"
76
77 def close(self):
78 """
79 Close connection to server
80 """
81 raise NotImplementedError, "Implement this method in child class"
82
83 def mkdir(self, remotefolder):
84 """
85 Create a folder remotely
86 """
87 raise NotImplementedError, "Implement this method in child class"
88
89 def cd(self, remotefolder):
90 """
91 Change working directory in remote server
92 """
93 raise NotImplementedError, "Implement this method in child class"
94
95 def download(self, filename, localfolder=None):
96 """
97 Download a file from server to local host
98 """
99 raise NotImplementedError, "Implement this method in child class"
100
101 def sendFile(self, fullfilename):
102 """
103 sendFile method is used to upload a local file to the current directory in remote server
104
105 Inputs:
106 fullfilename - full path name of local file to store in remote directory
107
108 Returns:
109 0 in error case else 1
110 """
111 raise NotImplementedError, "Implement this method in child class"
112
113 def upload(self, fullfilename, remotefolder=None):
114 """
115 upload method is used to upload a local file to remote directory. This method changes
116 working directory before sending a file.
117
118 Inputs:
119 fullfilename - full path name of local file to store in remote directory
120
121 remotefolder - remote directory
122
123 Returns:
124 0 in error case else 1
125 """
126 print "[Remote Server] Uploading %s to %s:%s" %(fullfilename, self.server, self.remotefolder)
127
128 if not self.status:
129 return 0
130
131 if remotefolder == None:
132 remotefolder = self.remotefolder
133
134 if not self.cd(remotefolder):
135 return 0
136
137 if not self.sendFile(fullfilename):
138 print "[Remote Server] Error uploading file %s" %fullfilename
139 return 0
140
141 print "[Remote Server] upload finished successfully"
142
143 return 1
144
145 def delete(self, filename):
146 """
147 Remove a file from remote server
148 """
149 pass
150
151 def updateFileList(self, fileList):
152 """
153 Remove a file from remote server
154 """
155
156 if fileList == self.fileList:
157 return 1
158
159 init = time.time()
160
161 while(self.bussy):
162 sleep(0.1)
163 if time.time() - init > 2*self.period:
164 return 0
165
166 self.fileList = fileList
167
168 return 1
169
170 def run(self):
171
172 if not self.cd(self.remotefolder):
173 raise ValueError, "It could not change to the new remote directory: %s" %remotefolder
174
175 while True:
176
177 sleep(self.period)
178
179 self.bussy = True
180
181 for thisFile in self.fileList:
182 self.upload(thisFile, self.remotefolder)
183
184 self.bussy = False
185
186 if self.stopFlag:
187 break
188
189 print "[Remote Server] Thread stopped successfully"
190
191 class FTPClient(Remote):
192
193 __ftpClientObj = None
194
195 def __init__(self, server, username, password, remotefolder, period=60):
196 """
197 """
198 Remote.__init__(self, server, username, password, remotefolder, period)
199
200 def open(self, server, username, password, remotefolder):
201
202 """
203 This method is used to set FTP parameters and establish a connection to remote server
204
205 Inputs:
206 server - remote server IP Address
207
208 username - remote server Username
209
210 password - remote server password
211
212 remotefolder - remote server current working directory
213
214 Return: void
215
216 Affects:
217 self.status - in case of error or fail connection this parameter is set to 0 else 1
218
219 """
220
221 if server == None:
222 raise ValueError, "FTP server should be defined"
223
224 if username == None:
225 raise ValueError, "FTP username should be defined"
226
227 if password == None:
228 raise ValueError, "FTP password should be defined"
229
230 if remotefolder == None:
231 raise ValueError, "FTP remote folder should be defined"
232
233 try:
234 ftpClientObj = ftplib.FTP(server)
235 except ftplib.all_errors:
236 print "FTP server connection fail: %s" %server
237 self.status = 0
238 return 0
239
240 try:
241 ftpClientObj.login(username, password)
242 except ftplib.all_errors:
243 print "FTP username or password are incorrect"
244 self.status = 0
245 return 0
246
247 if remotefolder == None:
248 remotefolder = ftpClientObj.pwd()
249 else:
250 try:
251 ftpClientObj.cwd(remotefolder)
252 except ftplib.all_errors:
253 print "FTP remote folder is invalid: %s" %remotefolder
254 remotefolder = ftpClientObj.pwd()
255
256 self.server = server
257 self.username = username
258 self.password = password
259 self.remotefolder = remotefolder
260 self.__ftpClientObj = ftpClientObj
261 self.status = 1
262
263 return 1
264
265 def close(self):
266 """
267 Close connection to remote server
268 """
269 if not self.status:
270 return 0
271
272 self.__ftpClientObj.close()
273
274 def mkdir(self, remotefolder):
275 """
276 mkdir is used to make a new directory in remote server
277
278 Input:
279 remotefolder - directory name
280
281 Return:
282 0 in error case else 1
283 """
284 if not self.status:
285 return 0
286
287 try:
288 self.__ftpClientObj.mkd(dirname)
289 except ftplib.all_errors:
290 print "Error creating remote folder: %s" %remotefolder
291 return 0
292
293 return 1
294
295 def cd(self, remotefolder):
296 """
297 cd is used to change remote working directory on server
298
299 Input:
300 remotefolder - current working directory
301
302 Affects:
303 self.remotefolder
304
305 Return:
306 0 in case of error else 1
307 """
308 if not self.status:
309 return 0
310
311 if remotefolder == self.remotefolder:
312 return 1
313
314 try:
315 self.__ftpClientObj.cwd(remotefolder)
316 except ftplib.all_errors:
317 print 'Error changing to %s' %remotefolder
318 print 'Trying to create remote folder'
319
320 if not self.mkdir(remotefolder):
321 print 'Remote folder could not be created'
322 return 0
323
324 try:
325 self.__ftpClientObj.cwd(remotefolder)
326 except ftplib.all_errors:
327 return 0
328
329 self.remotefolder = remotefolder
330
331 return 1
332
333 def sendFile(self, fullfilename):
334
335 if not self.status:
336 return 0
337
338 file = open(fullfilename, 'rb')
339
340 filename = os.path.split(fullfilename)[-1]
341
342 command = "STOR %s" %filename
343
344 try:
345 self.__ftpClientObj.storbinary(command, file)
346 except ftplib.all_errors:
347 return 0
348
349 try:
350 self.__ftpClientObj.sendcmd('SITE CHMOD 755 ' + filename)
351 except ftplib.all_errors, e:
352 print e
353
354 file.close()
355
356 return 1
357
358 class SSHClient(Remote):
359
360 __sshClientObj = None
361 __scpClientObj = None
362
363 def __init__(self, server, username, password, remotefolder, period=60):
364 """
365 """
366 Remote.__init__(self, server, username, password, remotefolder, period)
367
368 def open(self, server, username, password, remotefolder, port=22):
369
370 """
371 This method is used to set SSH parameters and establish a connection to a remote server
372
373 Inputs:
374 server - remote server IP Address
375
376 username - remote server Username
377
378 password - remote server password
379
380 remotefolder - remote server current working directory
381
382 Return: void
383
384 Affects:
385 self.status - in case of error or fail connection this parameter is set to 0 else 1
386
387 """
388
389 if server == None:
390 raise ValueError, "SSH server should be defined"
391
392 if username == None:
393 raise ValueError, "SSH username should be defined"
394
395 if password == None:
396 raise ValueError, "SSH password should be defined"
397
398 if remotefolder == None:
399 raise ValueError, "SSH remote folder should be defined"
400
401 try:
402 sshClientObj = paramiko.SSHClient()
403 except:
404 print "SSH server connection fail: %s" %server
405 self.status = 0
406 return 0
407
408 sshClientObj.load_system_host_keys()
409 sshClientObj.set_missing_host_key_policy(paramiko.WarningPolicy())
410
411 try:
412 sshClientObj.connect(server, username=username, password=password, port=port)
413 except :
414 print "SSH username or password are incorrect: %s"
415 self.status = 0
416 return 0
417
418 scpClientObj = scp.SCPClient(sshClientObj.get_transport(), socket_timeout=30)
419
420 if remotefolder == None:
421 remotefolder = self.pwd()
422
423 self.server = server
424 self.username = username
425 self.password = password
426 self.remotefolder = remotefolder
427 self.__sshClientObj = sshClientObj
428 self.__scpClientObj = scpClientObj
429 self.status = 1
430
431 return 1
432
433 def close(self):
434 """
435 Close connection to remote server
436 """
437 if not self.status:
438 return 0
439
440 self.__sshObj.close()
441
442 def mkdir(self, remotefolder):
443 """
444 mkdir is used to make a new directory in remote server
445
446 Input:
447 remotefolder - directory name
448
449 Return:
450 0 in error case else 1
451 """
452 if not self.status:
453 return 0
454
455 stdin, stdout, stderr = self.__sshClientObj.exec_command('mkdir %s' %remotefolder)
456 result = stderr.readlines()[0]
457
458 if len(result) > 1:
459 return 0
460
461 return 1
462
463 def pwd(self):
464
465 if not self.status:
466 return None
467
468 stdin, stdout, stderr = self.__sshClientObj.exec_command('pwd')
469 result = stdout.readlines()[0]
470
471 if len(result) < 1:
472 return None
473
474 return result[:-1]
475
476 def cd(self, remotefolder):
477 """
478 cd is used to change remote working directory on server
479
480 Input:
481 remotefolder - current working directory
482
483 Affects:
484 self.remotefolder
485
486 Return:
487 0 in case of error else 1
488 """
489 if not self.status:
490 return 0
491
492 if remotefolder == self.remotefolder:
493 return 1
494
495 self.remotefolder = remotefolder
496
497 return 1
498
499 def sendFile(self, fullfilename):
500
501 if not self.status:
502 return 0
503
504 try:
505 self.__scpClientObj.put(fullfilename, remote_path=self.remotefolder)
506 except:
507 return 0
508
509 return 1
510
511 class SendToServer(ProcessingUnit):
512
513 def __init__(self):
514
515 ProcessingUnit.__init__(self)
516
517 self.isConfig = False
518 self.clientObj = None
519
520 def setup(self, server, username, password, remotefolder, localfolder, ext='.png', period=60, protocol='ftp'):
521
522 self.clientObj = None
523 self.localfolder = localfolder
524 self.ext = ext
525 self.period = period
526
527 if str.lower(protocol) == 'ftp':
528 self.clientObj = FTPClient(server, username, password, remotefolder, period)
529
530 if str.lower(protocol) == 'ssh':
531 self.clientObj = SSHClient(server, username, password, remotefolder, period)
532
533 if not self.clientObj:
534 raise ValueError, "%s has been chosen as remote access protocol but it is not valid" %protocol
535
536 self.clientObj.start()
537
538 def findFiles(self):
539
540 filenameList = glob.glob1(self.localfolder, '*%s' %self.ext)
541
542 if len(filenameList) < 1:
543 return []
544
545 fullfilenameList = [os.path.join(self.localfolder, thisFile) for thisFile in filenameList]
546
547 return fullfilenameList
548
549 def run(self, **kwargs):
550
551 if not self.isConfig:
552 self.init = time.time()
553 self.setup(**kwargs)
554 self.isConfig = True
555
556 if time.time() - self.init >= self.period:
557 fullfilenameList = self.findFiles()
558 self.clientObj.updateFileList(fullfilenameList)
559 self.init = time.time()
560
561 def close(self):
562 print "[Remote Server] Stopping thread"
563 self.clientObj.stop()
564
565
10 class FTP(object):
566 class FTP(object):
11 """
567 """
12 Ftp is a public class used to define custom File Transfer Protocol from "ftplib" python module
568 Ftp is a public class used to define custom File Transfer Protocol from "ftplib" python module
13
569
14 Non-standard Python modules used: None
570 Non-standard Python modules used: None
15
571
16 Written by "Daniel Suarez":mailto:daniel.suarez@jro.igp.gob.pe Oct. 26, 2010
572 Written by "Daniel Suarez":mailto:daniel.suarez@jro.igp.gob.pe Oct. 26, 2010
17 """
573 """
18
574
19 def __init__(self,server = None, username=None, password=None, remotefolder=None):
575 def __init__(self,server = None, username=None, password=None, remotefolder=None):
20 """
576 """
21 This method is used to setting parameters for FTP and establishing connection to remote server
577 This method is used to setting parameters for FTP and establishing connection to remote server
22
578
23 Inputs:
579 Inputs:
24 server - remote server IP Address
580 server - remote server IP Address
25
581
26 username - remote server Username
582 username - remote server Username
27
583
28 password - remote server password
584 password - remote server password
29
585
30 remotefolder - remote server current working directory
586 remotefolder - remote server current working directory
31
587
32 Return: void
588 Return: void
33
589
34 Affects:
590 Affects:
35 self.status - in Error Case or Connection Failed this parameter is set to 1 else 0
591 self.status - in Error Case or Connection Failed this parameter is set to 1 else 0
36
592
37 self.folderList - sub-folder list of remote folder
593 self.folderList - sub-folder list of remote folder
38
594
39 self.fileList - file list of remote folder
595 self.fileList - file list of remote folder
40
596
41
597
42 """
598 """
43
599
44 if ((server == None) and (username==None) and (password==None) and (remotefolder==None)):
600 if ((server == None) and (username==None) and (password==None) and (remotefolder==None)):
45 server, username, password, remotefolder = self.parmsByDefault()
601 server, username, password, remotefolder = self.parmsByDefault()
46
602
47 self.server = server
603 self.server = server
48 self.username = username
604 self.username = username
49 self.password = password
605 self.password = password
50 self.remotefolder = remotefolder
606 self.remotefolder = remotefolder
51 self.file = None
607 self.file = None
52 self.ftp = None
608 self.ftp = None
53 self.status = 0
609 self.status = 0
54
610
55 try:
611 try:
56 self.ftp = ftplib.FTP(self.server)
612 self.ftp = ftplib.FTP(self.server)
57 self.ftp.login(self.username,self.password)
613 self.ftp.login(self.username,self.password)
58 self.ftp.cwd(self.remotefolder)
614 self.ftp.cwd(self.remotefolder)
59 # print 'Connect to FTP Server: Successfully'
615 # print 'Connect to FTP Server: Successfully'
60
616
61 except ftplib.all_errors:
617 except ftplib.all_errors:
62 print 'Error FTP Service'
618 print 'Error FTP Service'
63 self.status = 1
619 self.status = 1
64 return
620 return
65
621
66
622
67
623
68 self.dirList = []
624 self.dirList = []
69
625
70 try:
626 try:
71 self.dirList = self.ftp.nlst()
627 self.dirList = self.ftp.nlst()
72
628
73 except ftplib.error_perm, resp:
629 except ftplib.error_perm, resp:
74 if str(resp) == "550 No files found":
630 if str(resp) == "550 No files found":
75 print "no files in this directory"
631 print "no files in this directory"
76 self.status = 1
632 self.status = 1
77 return
633 return
78
634
79 except ftplib.all_errors:
635 except ftplib.all_errors:
80 print 'Error Displaying Dir-Files'
636 print 'Error Displaying Dir-Files'
81 self.status = 1
637 self.status = 1
82 return
638 return
83
639
84 self.fileList = []
640 self.fileList = []
85 self.folderList = []
641 self.folderList = []
86 #only for test
642 #only for test
87 for f in self.dirList:
643 for f in self.dirList:
88 name, ext = os.path.splitext(f)
644 name, ext = os.path.splitext(f)
89 if ext != '':
645 if ext != '':
90 self.fileList.append(f)
646 self.fileList.append(f)
91 # print 'filename: %s - size: %d'%(f,self.ftp.size(f))
647 # print 'filename: %s - size: %d'%(f,self.ftp.size(f))
92
648
93 def parmsByDefault(self):
649 def parmsByDefault(self):
94 server = 'jro-app.igp.gob.pe'
650 server = 'jro-app.igp.gob.pe'
95 username = 'wmaster'
651 username = 'wmaster'
96 password = 'mst2010vhf'
652 password = 'mst2010vhf'
97 remotefolder = '/home/wmaster/graficos'
653 remotefolder = '/home/wmaster/graficos'
98
654
99 return server, username, password, remotefolder
655 return server, username, password, remotefolder
100
656
101
657
102 def mkd(self,dirname):
658 def mkd(self,dirname):
103 """
659 """
104 mkd is used to make directory in remote server
660 mkd is used to make directory in remote server
105
661
106 Input:
662 Input:
107 dirname - directory name
663 dirname - directory name
108
664
109 Return:
665 Return:
110 1 in error case else 0
666 1 in error case else 0
111 """
667 """
112 try:
668 try:
113 self.ftp.mkd(dirname)
669 self.ftp.mkd(dirname)
114 except:
670 except:
115 print 'Error creating remote folder:%s'%dirname
671 print 'Error creating remote folder:%s'%dirname
116 return 1
672 return 1
117
673
118 return 0
674 return 0
119
675
120
676
121 def delete(self,filename):
677 def delete(self,filename):
122 """
678 """
123 delete is used to delete file in current working directory of remote server
679 delete is used to delete file in current working directory of remote server
124
680
125 Input:
681 Input:
126 filename - filename to delete in remote folder
682 filename - filename to delete in remote folder
127
683
128 Return:
684 Return:
129 1 in error case else 0
685 1 in error case else 0
130 """
686 """
131
687
132 try:
688 try:
133 self.ftp.delete(filename)
689 self.ftp.delete(filename)
134 except:
690 except:
135 print 'Error deleting remote file:%s'%filename
691 print 'Error deleting remote file:%s'%filename
136 return 1
692 return 1
137
693
138 return 0
694 return 0
139
695
140 def download(self,filename,localfolder):
696 def download(self,filename,localfolder):
141 """
697 """
142 download is used to downloading file from remote folder into local folder
698 download is used to downloading file from remote folder into local folder
143
699
144 Inputs:
700 Inputs:
145 filename - filename to donwload
701 filename - filename to donwload
146
702
147 localfolder - directory local to store filename
703 localfolder - directory local to store filename
148
704
149 Returns:
705 Returns:
150 self.status - 1 in error case else 0
706 self.status - 1 in error case else 0
151 """
707 """
152
708
153 self.status = 0
709 self.status = 0
154
710
155
711
156 if not(filename in self.fileList):
712 if not(filename in self.fileList):
157 print 'filename:%s not exists'%filename
713 print 'filename:%s not exists'%filename
158 self.status = 1
714 self.status = 1
159 return self.status
715 return self.status
160
716
161 newfilename = os.path.join(localfolder,filename)
717 newfilename = os.path.join(localfolder,filename)
162
718
163 self.file = open(newfilename, 'wb')
719 self.file = open(newfilename, 'wb')
164
720
165 try:
721 try:
166 print 'Download: ' + filename
722 print 'Download: ' + filename
167 self.ftp.retrbinary('RETR ' + filename, self.__handleDownload)
723 self.ftp.retrbinary('RETR ' + filename, self.__handleDownload)
168 print 'Download Complete'
724 print 'Download Complete'
169 except ftplib.all_errors:
725 except ftplib.all_errors:
170 print 'Error Downloading ' + filename
726 print 'Error Downloading ' + filename
171 self.status = 1
727 self.status = 1
172 return self.status
728 return self.status
173
729
174 self.file.close()
730 self.file.close()
175
731
176 return self.status
732 return self.status
177
733
178
734
179 def __handleDownload(self,block):
735 def __handleDownload(self,block):
180 """
736 """
181 __handleDownload is used to handle writing file
737 __handleDownload is used to handle writing file
182 """
738 """
183 self.file.write(block)
739 self.file.write(block)
184
740
185
741
186 def upload(self,filename,remotefolder=None):
742 def upload(self,filename,remotefolder=None):
187 """
743 """
188 upload is used to uploading local file to remote directory
744 upload is used to uploading local file to remote directory
189
745
190 Inputs:
746 Inputs:
191 filename - full path name of local file to store in remote directory
747 filename - full path name of local file to store in remote directory
192
748
193 remotefolder - remote directory
749 remotefolder - remote directory
194
750
195 Returns:
751 Returns:
196 self.status - 1 in error case else 0
752 self.status - 1 in error case else 0
197 """
753 """
198
754
199 if remotefolder == None:
755 if remotefolder == None:
200 remotefolder = self.remotefolder
756 remotefolder = self.remotefolder
201
757
202 self.status = 0
758 self.status = 0
203
759
204 try:
760 try:
205 self.ftp.cwd(remotefolder)
761 self.ftp.cwd(remotefolder)
206
762
207 self.file = open(filename, 'rb')
763 self.file = open(filename, 'rb')
208
764
209 (head, tail) = os.path.split(filename)
765 (head, tail) = os.path.split(filename)
210
766
211 command = "STOR " + tail
767 command = "STOR " + tail
212
768
213 print 'Uploading: ' + tail
769 print 'Uploading: ' + tail
214 self.ftp.storbinary(command, self.file)
770 self.ftp.storbinary(command, self.file)
215 print 'Upload Completed'
771 print 'Upload Completed'
216
772
217 except ftplib.all_errors:
773 except ftplib.all_errors:
218 print 'Error Uploading ' + tail
774 print 'Error Uploading ' + tail
219 self.status = 1
775 self.status = 1
220 return self.status
776 return self.status
221
777
222 self.file.close()
778 self.file.close()
223
779
224 #back to initial directory in __init__()
780 #back to initial directory in __init__()
225 self.ftp.cwd(self.remotefolder)
781 self.ftp.cwd(self.remotefolder)
226
782
227 return self.status
783 return self.status
228
784
229
785
230 def dir(self,remotefolder):
786 def dir(self,remotefolder):
231 """
787 """
232 dir is used to change working directory of remote server and get folder and file list
788 dir is used to change working directory of remote server and get folder and file list
233
789
234 Input:
790 Input:
235 remotefolder - current working directory
791 remotefolder - current working directory
236
792
237 Affects:
793 Affects:
238 self.fileList - file list of working directory
794 self.fileList - file list of working directory
239
795
240 Return:
796 Return:
241 infoList - list with filenames and size of file in bytes
797 infoList - list with filenames and size of file in bytes
242
798
243 self.folderList - folder list
799 self.folderList - folder list
244 """
800 """
245
801
246 self.remotefolder = remotefolder
802 self.remotefolder = remotefolder
247 print 'Change to ' + self.remotefolder
803 print 'Change to ' + self.remotefolder
248 try:
804 try:
249 self.ftp.cwd(remotefolder)
805 self.ftp.cwd(remotefolder)
250 except ftplib.all_errors:
806 except ftplib.all_errors:
251 print 'Error Change to ' + self.remotefolder
807 print 'Error Change to ' + self.remotefolder
252 infoList = None
808 infoList = None
253 self.folderList = None
809 self.folderList = None
254 return infoList,self.folderList
810 return infoList,self.folderList
255
811
256 self.dirList = []
812 self.dirList = []
257
813
258 try:
814 try:
259 self.dirList = self.ftp.nlst()
815 self.dirList = self.ftp.nlst()
260
816
261 except ftplib.error_perm, resp:
817 except ftplib.error_perm, resp:
262 if str(resp) == "550 No files found":
818 if str(resp) == "550 No files found":
263 print "no files in this directory"
819 print "no files in this directory"
264 infoList = None
820 infoList = None
265 self.folderList = None
821 self.folderList = None
266 return infoList,self.folderList
822 return infoList,self.folderList
267 except ftplib.all_errors:
823 except ftplib.all_errors:
268 print 'Error Displaying Dir-Files'
824 print 'Error Displaying Dir-Files'
269 infoList = None
825 infoList = None
270 self.folderList = None
826 self.folderList = None
271 return infoList,self.folderList
827 return infoList,self.folderList
272
828
273 infoList = []
829 infoList = []
274 self.fileList = []
830 self.fileList = []
275 self.folderList = []
831 self.folderList = []
276 for f in self.dirList:
832 for f in self.dirList:
277 name,ext = os.path.splitext(f)
833 name,ext = os.path.splitext(f)
278 if ext != '':
834 if ext != '':
279 self.fileList.append(f)
835 self.fileList.append(f)
280 value = (f,self.ftp.size(f))
836 value = (f,self.ftp.size(f))
281 infoList.append(value)
837 infoList.append(value)
282
838
283 if ext == '':
839 if ext == '':
284 self.folderList.append(f)
840 self.folderList.append(f)
285
841
286 return infoList,self.folderList
842 return infoList,self.folderList
287
843
288
844
289 def close(self):
845 def close(self):
290 """
846 """
291 close is used to close and end FTP connection
847 close is used to close and end FTP connection
292
848
293 Inputs: None
849 Inputs: None
294
850
295 Return: void
851 Return: void
296
852
297 """
853 """
298 self.ftp.close()
854 self.ftp.close()
299
855
300 class SendByFTP(Operation):
856 class SendByFTP(Operation):
857
301 def __init__(self):
858 def __init__(self):
859
302 self.status = 1
860 self.status = 1
303 self.counter = 0
861 self.counter = 0
304
862
305 def error_print(self, ValueError):
863 def error_print(self, ValueError):
864
306 print ValueError, 'Error FTP'
865 print ValueError, 'Error FTP'
307 print "don't worry the program is running..."
866 print "don't worry the program is running..."
308
867
309 def worker_ftp(self, server, username, password, remotefolder, filenameList):
868 def worker_ftp(self, server, username, password, remotefolder, filenameList):
310
869
311 self.ftpObj = FTP(server, username, password, remotefolder)
870 self.ftpClientObj = FTP(server, username, password, remotefolder)
312 for filename in filenameList:
871 for filename in filenameList:
313 self.ftpObj.upload(filename)
872 self.ftpClientObj.upload(filename)
314 self.ftpObj.close()
873 self.ftpClientObj.close()
315
874
316 def ftp_thread(self, server, username, password, remotefolder):
875 def ftp_thread(self, server, username, password, remotefolder):
317 if not(self.status):
876 if not(self.status):
318 return
877 return
319
878
320 p = multiprocessing.Process(target=self.worker_ftp, args=(server, username, password, remotefolder, self.filenameList,))
879 p = multiprocessing.Process(target=self.worker_ftp, args=(server, username, password, remotefolder, self.filenameList,))
321 p.start()
880 p.start()
322
881
323 p.join(3)
882 p.join(3)
324
883
325 if p.is_alive():
884 if p.is_alive():
326 p.terminate()
885 p.terminate()
327 p.join()
886 p.join()
328 print 'killing ftp process...'
887 print 'killing ftp process...'
329 self.status = 0
888 self.status = 0
330 return
889 return
331
890
332 self.status = 1
891 self.status = 1
333 return
892 return
334
893
335 def filterByExt(self, ext, localfolder):
894 def filterByExt(self, ext, localfolder):
336 fnameList = glob.glob1(localfolder,ext)
895 fnameList = glob.glob1(localfolder,ext)
337 self.filenameList = [os.path.join(localfolder,x) for x in fnameList]
896 self.filenameList = [os.path.join(localfolder,x) for x in fnameList]
338
897
339 if len(self.filenameList) == 0:
898 if len(self.filenameList) == 0:
340 self.status = 0
899 self.status = 0
341
900
342 def run(self, dataOut, ext, localfolder, remotefolder, server, username, password, period=1):
901 def run(self, dataOut, ext, localfolder, remotefolder, server, username, password, period=1):
343
902
344 self.counter += 1
903 self.counter += 1
345 if self.counter >= period:
904 if self.counter >= period:
346 self.filterByExt(ext, localfolder)
905 self.filterByExt(ext, localfolder)
347
906
348 self.ftp_thread(server, username, password, remotefolder)
907 self.ftp_thread(server, username, password, remotefolder)
349
908
350 self.counter = 0
909 self.counter = 0
351
910
352 self.status = 1
911 self.status = 1
353
912
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now