simplify some params
[debian/gnuradio] / gr-wxgui / src / python / common.py
1 #
2 # Copyright 2008 Free Software Foundation, Inc.
3 #
4 # This file is part of GNU Radio
5 #
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10 #
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20 #
21
22 ##################################################
23 # conditional disconnections of wx flow graph
24 ##################################################
25 import wx
26 from gnuradio import gr
27
28 class wxgui_hb(object):
29         """
30         The wxgui hier block helper/wrapper class:
31         A hier block should inherit from this class to make use of the wxgui connect method.
32         To use, call wxgui_connect in place of regular connect; self.win must be defined.
33         The implementation will conditionally connect or disconnect the self (source) of the hb.
34         This condition depends on weather or not the window is visible with the parent notebooks.
35         This condition will be re-checked on every ui update event.
36         """
37
38         def wxgui_connect(self, *points):
39                 """
40                 Use wxgui connect when the first point is the self source of the hb.
41                 The win property of this object should be set to the wx window.
42                 When this method tries to connect self to the next point,
43                 it will conditionally make this connection based on the visibility state.
44                 All other points will be connected normally.
45                 """
46                 try:
47                         assert points[0] == self or points[0][0] == self
48                         self._conditional_connect(points[0], points[1])
49                         if len(points[1:]) > 1: self.connect(*points[1:])
50                 except (AssertionError, IndexError): self.connect(*points)
51
52         def _conditional_connect(self, source, sink):
53                 """
54                 Create a handler for visibility changes.
55                 Initially call the handler to setup the fg.
56                 Bind the handler to the visibility meta event.
57                 """
58                 handler = self._conditional_connect_handler_factory(source=source, sink=sink)
59                 handler(False, init=True) #initially connect
60                 self._bind_to_visible_event(win=self.win, handler=handler)
61
62         def _conditional_connect_handler_factory(self, source, sink):
63                 """
64                 Create a function that will handle the re-connections based on a flag.
65                 The current state of the connection is stored in the namespace.
66                 !!!#TODO This entire method could be replaced with a mute block that starves the stream.
67                 """
68                 nulls = list()
69                 cache = [None]
70                 size = self._hb.input_signature().sizeof_stream_item(0)
71                 def callback(visible, init=False):
72                         if visible == cache[0]: return
73                         cache[0] = visible
74                         if not init: self.lock()
75                         #print 'visible', visible, source, sink
76                         if visible:
77                                 if not init:
78                                         self.disconnect(source, nulls[0])
79                                         self.disconnect(nulls[1], nulls[2])
80                                         self.disconnect(nulls[2], sink)
81                                         while nulls: nulls.pop()
82                                 self.connect(source, sink)
83                         else:
84                                 if not init: self.disconnect(source, sink)
85                                 nulls.extend([gr.null_sink(size), gr.null_source(size), gr.head(size, 0)])
86                                 self.connect(source, nulls[0])
87                                 self.connect(nulls[1], nulls[2], sink)
88                         if not init: self.unlock()
89                 return callback
90
91         @staticmethod
92         def _bind_to_visible_event(win, handler):
93                 """
94                 Bind a handler to a window when its visibility changes.
95                 Specifically, call the handler when the window visibility changes.
96                 This condition is checked on every update ui event.
97                 @param win the wx window
98                 @param handler a function of 1 param
99                 """
100                 #is the window visible in the hierarchy
101                 def is_wx_window_visible(my_win):
102                         while True:
103                                 parent = my_win.GetParent()
104                                 if not parent: return True #reached the top of the hierarchy
105                                 #if we are hidden, then finish, otherwise keep traversing up
106                                 if isinstance(parent, wx.Notebook) and parent.GetCurrentPage() != my_win: return False
107                                 my_win = parent
108                 #call the handler, the arg is shown or not
109                 def handler_factory(my_win, my_handler):
110                         return lambda *args: my_handler(is_wx_window_visible(my_win))
111                 handler = handler_factory(win, handler)
112                 #bind the handler to all the parent notebooks
113                 win.Bind(wx.EVT_UPDATE_UI, handler)
114
115 ##################################################
116 # Helpful Functions
117 ##################################################
118
119 #A macro to apply an index to a key
120 index_key = lambda key, i: "%s_%d"%(key, i+1)
121
122 def _register_access_method(destination, controller, key):
123         """
124         Helper function for register access methods.
125         This helper creates distinct set and get methods for each key
126         and adds them to the destination object.
127         """
128         def set(value): controller[key] = value
129         setattr(destination, 'set_'+key, set)
130         def get(): return controller[key]
131         setattr(destination, 'get_'+key, get) 
132
133 def register_access_methods(destination, controller):
134         """
135         Register setter and getter functions in the destination object for all keys in the controller.
136         @param destination the object to get new setter and getter methods
137         @param controller the pubsub controller
138         """
139         for key in controller.keys(): _register_access_method(destination, controller, key)
140
141 ##################################################
142 # Input Watcher Thread
143 ##################################################
144 from gnuradio import gru
145
146 class input_watcher(gru.msgq_runner):
147         """
148         Input watcher thread runs forever.
149         Read messages from the message queue.
150         Forward messages to the message handler.
151         """
152         def __init__ (self, msgq, controller, msg_key, arg1_key='', arg2_key=''):
153                 self._controller = controller
154                 self._msg_key = msg_key
155                 self._arg1_key = arg1_key
156                 self._arg2_key = arg2_key
157                 gru.msgq_runner.__init__(self, msgq, self.handle_msg)
158
159         def handle_msg(self, msg):
160                 if self._arg1_key: self._controller[self._arg1_key] = msg.arg1()
161                 if self._arg2_key: self._controller[self._arg2_key] = msg.arg2()
162                 self._controller[self._msg_key] = msg.to_string()
163
164
165 ##################################################
166 # Shared Functions
167 ##################################################
168 import numpy
169 import math
170
171 def get_exp(num):
172         """
173         Get the exponent of the number in base 10.
174         @param num the floating point number
175         @return the exponent as an integer
176         """
177         if num == 0: return 0
178         return int(math.floor(math.log10(abs(num))))
179
180 def get_clean_num(num):
181         """
182         Get the closest clean number match to num with bases 1, 2, 5.
183         @param num the number
184         @return the closest number
185         """
186         if num == 0: return 0
187         sign = num > 0 and 1 or -1
188         exp = get_exp(num)
189         nums = numpy.array((1, 2, 5, 10))*(10**exp)
190         return sign*nums[numpy.argmin(numpy.abs(nums - abs(num)))]
191
192 def get_clean_incr(num):
193         """
194         Get the next higher clean number with bases 1, 2, 5.
195         @param num the number
196         @return the next higher number
197         """
198         num = get_clean_num(num)
199         exp = get_exp(num)
200         coeff = int(round(num/10**exp))
201         return {
202                 -5: -2,
203                 -2: -1,
204                 -1: -.5,
205                 1: 2,
206                 2: 5,
207                 5: 10,
208         }[coeff]*(10**exp)
209
210 def get_clean_decr(num):
211         """
212         Get the next lower clean number with bases 1, 2, 5.
213         @param num the number
214         @return the next lower number
215         """
216         num = get_clean_num(num)
217         exp = get_exp(num)
218         coeff = int(round(num/10**exp))
219         return {
220                 -5: -10,
221                 -2: -5,
222                 -1: -2,
223                 1: .5,
224                 2: 1,
225                 5: 2,
226         }[coeff]*(10**exp)
227
228 def get_min_max(samples):
229         """
230         Get the minimum and maximum bounds for an array of samples.
231         @param samples the array of real values
232         @return a tuple of min, max
233         """
234         scale_factor = 3
235         mean = numpy.average(samples)
236         rms = numpy.max([scale_factor*((numpy.sum((samples-mean)**2)/len(samples))**.5), .1])
237         min_val = mean - rms
238         max_val = mean + rms
239         return min_val, max_val
240
241 def get_min_max_fft(fft_samps):
242         """
243         Get the minimum and maximum bounds for an array of fft samples.
244         @param samples the array of real values
245         @return a tuple of min, max
246         """
247         #get the peak level (max of the samples)
248         peak_level = numpy.max(fft_samps)
249         #separate noise samples
250         noise_samps = numpy.sort(fft_samps)[:len(fft_samps)/2]
251         #get the noise floor
252         noise_floor = numpy.average(noise_samps)
253         #get the noise deviation
254         noise_dev = numpy.std(noise_samps)
255         #determine the maximum and minimum levels
256         max_level = peak_level
257         min_level = noise_floor - abs(2*noise_dev)
258         return min_level, max_level