removed unused import statements, thanks pyflakes
[debian/gnuradio] / grc / python / FlowGraph.py
1 """
2 Copyright 2008, 2009 Free Software Foundation, Inc.
3 This file is part of GNU Radio
4
5 GNU Radio Companion is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 GNU Radio Companion is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18 """
19
20 import expr_utils
21 from .. base.FlowGraph import FlowGraph as _FlowGraph
22 from .. gui.FlowGraph import FlowGraph as _GUIFlowGraph
23 import re
24
25 _variable_matcher = re.compile('^(variable\w*)$')
26 _parameter_matcher = re.compile('^(parameter)$')
27
28 class FlowGraph(_FlowGraph, _GUIFlowGraph):
29
30         def __init__(self, **kwargs):
31                 _FlowGraph.__init__(self, **kwargs)
32                 _GUIFlowGraph.__init__(self)
33                 self._eval_cache = dict()
34
35         def _eval(self, code, namespace, namespace_hash):
36                 """
37                 Evaluate the code with the given namespace.
38                 @param code a string with python code
39                 @param namespace a dict representing the namespace
40                 @param namespace_hash a unique hash for the namespace
41                 @return the resultant object
42                 """
43                 if not code: raise Exception, 'Cannot evaluate empty statement.'
44                 my_hash = hash(code) ^ namespace_hash
45                 #cache if does not exist
46                 if not self._eval_cache.has_key(my_hash):
47                         self._eval_cache[my_hash] = eval(code, namespace, namespace)
48                 #return from cache
49                 return self._eval_cache[my_hash]
50
51         def _get_io_signature(self, pad_key):
52                 """
53                 Get an io signature for this flow graph.
54                 The pad key determines the directionality of the io signature.
55                 @param pad_key a string of pad_source or pad_sink
56                 @return a dict with: type, nports, vlen, size
57                 """
58                 pads = filter(lambda b: b.get_key() == pad_key, self.get_enabled_blocks())
59                 if not pads: return {
60                         'nports': '0',
61                         'type': '',
62                         'vlen': '0',
63                         'size': '0',
64                 }
65                 pad = pads[0] #take only the first, user should not have more than 1
66                 #load io signature
67                 return {
68                         'nports': str(pad.get_param('nports').get_evaluated()),
69                         'type': str(pad.get_param('type').get_evaluated()),
70                         'vlen': str(pad.get_param('vlen').get_evaluated()),
71                         'size': pad.get_param('type').get_opt('size'),
72                 }
73
74         def get_input_signature(self):
75                 """
76                 Get the io signature for the input side of this flow graph.
77                 The io signature with be "0", "0" if no pad source is present.
78                 @return a string tuple of type, num_ports, port_size
79                 """
80                 return self._get_io_signature('pad_source')
81
82         def get_output_signature(self):
83                 """
84                 Get the io signature for the output side of this flow graph.
85                 The io signature with be "0", "0" if no pad sink is present.
86                 @return a string tuple of type, num_ports, port_size
87                 """
88                 return self._get_io_signature('pad_sink')
89
90         def get_imports(self):
91                 """
92                 Get a set of all import statments in this flow graph namespace.
93                 @return a set of import statements
94                 """
95                 imports = sum([block.get_imports() for block in self.get_enabled_blocks()], [])
96                 imports = sorted(set(imports))
97                 return imports
98
99         def get_variables(self):
100                 """
101                 Get a list of all variables in this flow graph namespace.
102                 Exclude paramterized variables.
103                 @return a sorted list of variable blocks in order of dependency (indep -> dep)
104                 """
105                 variables = filter(lambda b: _variable_matcher.match(b.get_key()), self.get_enabled_blocks())
106                 return expr_utils.sort_objects(variables, lambda v: v.get_id(), lambda v: v.get_var_make())
107
108         def get_parameters(self):
109                 """
110                 Get a list of all paramterized variables in this flow graph namespace.
111                 @return a list of paramterized variables
112                 """
113                 parameters = filter(lambda b: _parameter_matcher.match(b.get_key()), self.get_enabled_blocks())
114                 return parameters
115
116         def rewrite(self):
117                 """
118                 Flag the namespace to be renewed.
119                 """
120                 self._renew_eval_ns = True
121                 _FlowGraph.rewrite(self)
122
123         def evaluate(self, expr):
124                 """
125                 Evaluate the expression.
126                 @param expr the string expression
127                 @throw Exception bad expression
128                 @return the evaluated data
129                 """
130                 if self._renew_eval_ns:
131                         self._renew_eval_ns = False
132                         #reload namespace
133                         n = dict()
134                         #load imports
135                         for imp in self.get_imports():
136                                 try: exec imp in n
137                                 except: pass
138                         #load parameters
139                         np = dict()
140                         for parameter in self.get_parameters():
141                                 try:
142                                         e = eval(parameter.get_param('value').to_code(), n, n)
143                                         np[parameter.get_id()] = e
144                                 except: pass
145                         n.update(np) #merge param namespace
146                         #load variables
147                         for variable in self.get_variables():
148                                 try:
149                                         e = eval(variable.get_param('value').to_code(), n, n)
150                                         n[variable.get_id()] = e
151                                 except: pass
152                         #make namespace public
153                         self.n = n
154                         self.n_hash = hash(str(n))
155                 #evaluate
156                 e = self._eval(expr, self.n, self.n_hash)
157                 return e