Merge branch 'wip/wxgui' of http://gnuradio.org/git/jblum
[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 enable the copy block after the source (self).
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                         copy = gr.copy(self._hb.input_signature().sizeof_stream_item(0))
49                         handler = self._handler_factory(copy.set_enabled)
50                         handler(False) #initially disable the copy block
51                         self._bind_to_visible_event(win=self.win, handler=handler)
52                         points = list(points)
53                         points.insert(1, copy) #insert the copy block into the chain
54                 except (AssertionError, IndexError): pass
55                 self.connect(*points) #actually connect the blocks
56
57         @staticmethod
58         def _handler_factory(handler):
59                 """
60                 Create a function that will cache the visibility flag,
61                 and only call the handler when that flag changes.
62                 @param handler the function to call on a change
63                 @return a function of 1 argument
64                 """
65                 cache = [None]
66                 def callback(visible):
67                         if cache[0] == visible: return
68                         cache[0] = visible
69                         #print visible, handler
70                         handler(visible)
71                 return callback
72
73         @staticmethod
74         def _bind_to_visible_event(win, handler):
75                 """
76                 Bind a handler to a window when its visibility changes.
77                 Specifically, call the handler when the window visibility changes.
78                 This condition is checked on every update ui event.
79                 @param win the wx window
80                 @param handler a function of 1 param
81                 """
82                 #is the window visible in the hierarchy
83                 def is_wx_window_visible(my_win):
84                         while True:
85                                 parent = my_win.GetParent()
86                                 if not parent: return True #reached the top of the hierarchy
87                                 #if we are hidden, then finish, otherwise keep traversing up
88                                 if isinstance(parent, wx.Notebook) and parent.GetCurrentPage() != my_win: return False
89                                 my_win = parent
90                 #call the handler, the arg is shown or not
91                 def handler_factory(my_win, my_handler):
92                         return lambda *args: my_handler(is_wx_window_visible(my_win))
93                 handler = handler_factory(win, handler)
94                 #bind the handler to all the parent notebooks
95                 win.Bind(wx.EVT_UPDATE_UI, handler)
96
97 ##################################################
98 # Helpful Functions
99 ##################################################
100
101 #A macro to apply an index to a key
102 index_key = lambda key, i: "%s_%d"%(key, i+1)
103
104 def _register_access_method(destination, controller, key):
105         """
106         Helper function for register access methods.
107         This helper creates distinct set and get methods for each key
108         and adds them to the destination object.
109         """
110         def set(value): controller[key] = value
111         setattr(destination, 'set_'+key, set)
112         def get(): return controller[key]
113         setattr(destination, 'get_'+key, get) 
114
115 def register_access_methods(destination, controller):
116         """
117         Register setter and getter functions in the destination object for all keys in the controller.
118         @param destination the object to get new setter and getter methods
119         @param controller the pubsub controller
120         """
121         for key in controller.keys(): _register_access_method(destination, controller, key)
122
123 ##################################################
124 # Input Watcher Thread
125 ##################################################
126 from gnuradio import gru
127
128 class input_watcher(gru.msgq_runner):
129         """
130         Input watcher thread runs forever.
131         Read messages from the message queue.
132         Forward messages to the message handler.
133         """
134         def __init__ (self, msgq, controller, msg_key, arg1_key='', arg2_key=''):
135                 self._controller = controller
136                 self._msg_key = msg_key
137                 self._arg1_key = arg1_key
138                 self._arg2_key = arg2_key
139                 gru.msgq_runner.__init__(self, msgq, self.handle_msg)
140
141         def handle_msg(self, msg):
142                 if self._arg1_key: self._controller[self._arg1_key] = msg.arg1()
143                 if self._arg2_key: self._controller[self._arg2_key] = msg.arg2()
144                 self._controller[self._msg_key] = msg.to_string()
145
146
147 ##################################################
148 # Shared Functions
149 ##################################################
150 import numpy
151 import math
152
153 def get_exp(num):
154         """
155         Get the exponent of the number in base 10.
156         @param num the floating point number
157         @return the exponent as an integer
158         """
159         if num == 0: return 0
160         return int(math.floor(math.log10(abs(num))))
161
162 def get_clean_num(num):
163         """
164         Get the closest clean number match to num with bases 1, 2, 5.
165         @param num the number
166         @return the closest number
167         """
168         if num == 0: return 0
169         sign = num > 0 and 1 or -1
170         exp = get_exp(num)
171         nums = numpy.array((1, 2, 5, 10))*(10**exp)
172         return sign*nums[numpy.argmin(numpy.abs(nums - abs(num)))]
173
174 def get_clean_incr(num):
175         """
176         Get the next higher clean number with bases 1, 2, 5.
177         @param num the number
178         @return the next higher number
179         """
180         num = get_clean_num(num)
181         exp = get_exp(num)
182         coeff = int(round(num/10**exp))
183         return {
184                 -5: -2,
185                 -2: -1,
186                 -1: -.5,
187                 1: 2,
188                 2: 5,
189                 5: 10,
190         }[coeff]*(10**exp)
191
192 def get_clean_decr(num):
193         """
194         Get the next lower clean number with bases 1, 2, 5.
195         @param num the number
196         @return the next lower number
197         """
198         num = get_clean_num(num)
199         exp = get_exp(num)
200         coeff = int(round(num/10**exp))
201         return {
202                 -5: -10,
203                 -2: -5,
204                 -1: -2,
205                 1: .5,
206                 2: 1,
207                 5: 2,
208         }[coeff]*(10**exp)
209
210 def get_min_max(samples):
211         """
212         Get the minimum and maximum bounds for an array of samples.
213         @param samples the array of real values
214         @return a tuple of min, max
215         """
216         scale_factor = 3
217         mean = numpy.average(samples)
218         rms = numpy.max([scale_factor*((numpy.sum((samples-mean)**2)/len(samples))**.5), .1])
219         min_val = mean - rms
220         max_val = mean + rms
221         return min_val, max_val
222
223 def get_min_max_fft(fft_samps):
224         """
225         Get the minimum and maximum bounds for an array of fft samples.
226         @param samples the array of real values
227         @return a tuple of min, max
228         """
229         #get the peak level (max of the samples)
230         peak_level = numpy.max(fft_samps)
231         #separate noise samples
232         noise_samps = numpy.sort(fft_samps)[:len(fft_samps)/2]
233         #get the noise floor
234         noise_floor = numpy.average(noise_samps)
235         #get the noise deviation
236         noise_dev = numpy.std(noise_samps)
237         #determine the maximum and minimum levels
238         max_level = peak_level
239         min_level = noise_floor - abs(2*noise_dev)
240         return min_level, max_level