added include <cstdio> statements in several files to make it compatible with g+...
[debian/gnuradio] / grc / src / platforms / python / Generator.py
1 """
2 Copyright 2008 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 os
21 import subprocess
22 from Cheetah.Template import Template
23 from utils import expr_utils
24 from Constants import \
25         TOP_BLOCK_FILE_MODE, HIER_BLOCK_FILE_MODE, \
26         HIER_BLOCKS_LIB_DIR, PYEXEC, \
27         FLOW_GRAPH_TEMPLATE
28 from utils import convert_hier
29 from ... gui import Messages
30
31 class Generator(object):
32
33         def __init__(self, flow_graph, file_path):
34                 """
35                 Initialize the generator object.
36                 Determine the file to generate.
37                 @param flow_graph the flow graph object
38                 @param file_path the path to write the file to
39                 """
40                 self._flow_graph = flow_graph
41                 self._generate_options = self._flow_graph.get_option('generate_options')
42                 if self._generate_options == 'hb':
43                         self._mode = HIER_BLOCK_FILE_MODE
44                         dirname = HIER_BLOCKS_LIB_DIR
45                 else:
46                         self._mode = TOP_BLOCK_FILE_MODE
47                         dirname = os.path.dirname(file_path)
48                 filename = self._flow_graph.get_option('id') + '.py'
49                 self._file_path = os.path.join(dirname, filename)
50
51         def get_file_path(self): return self._file_path
52
53         def write(self):
54                 #do throttle warning
55                 all_keys = ' '.join(map(lambda b: b.get_key(), self._flow_graph.get_enabled_blocks()))
56                 if ('usrp' not in all_keys) and ('audio' not in all_keys) and ('throttle' not in all_keys) and self._generate_options != 'hb':
57                         Messages.send_warning('''\
58 This flow graph may not have flow control: no audio or usrp blocks found. \
59 Add a Misc->Throttle block to your flow graph to avoid CPU congestion.''')
60                 #generate
61                 open(self.get_file_path(), 'w').write(str(self))
62                 if self._generate_options == 'hb':
63                         #convert hier block to xml wrapper
64                         convert_hier.convert_hier(self._flow_graph, self.get_file_path())
65                 os.chmod(self.get_file_path(), self._mode)
66
67         def get_popen(self):
68                 """
69                 Execute this python flow graph.
70                 @return a popen object
71                 """
72                 #execute
73                 cmds = [PYEXEC, '-u', self.get_file_path()] #-u is unbuffered stdio
74                 if self._generate_options == 'no_gui':
75                         cmds = ['xterm', '-e'] + cmds
76                 p = subprocess.Popen(args=cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, universal_newlines=True)
77                 return p
78
79         def __str__(self):
80                 """
81                 Convert the flow graph to python code.
82                 @return a string of python code
83                 """
84                 imports = self._flow_graph.get_imports()
85                 variables = self._flow_graph.get_variables()
86                 parameters = self._flow_graph.get_parameters()
87                 #list of variables with controls
88                 controls = filter(lambda v: v.get_key().startswith('variable_'), variables)
89                 #list of blocks not including variables and imports and parameters and disabled
90                 blocks = sorted(self._flow_graph.get_enabled_blocks(), lambda x, y: cmp(x.get_id(), y.get_id()))
91                 probes = filter(lambda b: b.get_key().startswith('probe_'), blocks) #ensure probes are last in the block list
92                 blocks = filter(lambda b: b not in (imports + parameters + variables + probes), blocks) + probes
93                 #list of connections where each endpoint is enabled
94                 connections = self._flow_graph.get_enabled_connections()
95                 #list of variable names
96                 var_ids = [var.get_id() for var in parameters + variables]
97                 #list of callbacks (prepend self.)
98                 callbacks = [
99                         expr_utils.expr_prepend(cb, var_ids, 'self.')
100                         for cb in sum([block.get_callbacks() for block in self._flow_graph.get_enabled_blocks()], [])
101                 ]
102                 #map var id to the expression (prepend self.)
103                 var_id2expr = dict(
104                         [(var.get_id(), expr_utils.expr_prepend(var.get_make().split('\n')[0], var_ids, 'self.'))
105                         for var in parameters + variables]
106                 )
107                 #create graph structure for variables
108                 variable_graph = expr_utils.get_graph(var_id2expr)
109                 #map var id to direct dependents
110                 #for each var id, make a list of all 2nd order edges
111                 #use all edges of that id that are not also 2nd order edges
112                 #meaning: list variables the ONLY depend directly on this variable
113                 #and not variables that also depend indirectly on this variable
114                 var_id2deps = dict(
115                         [(var_id, filter(lambda e: e not in sum([list(variable_graph.get_edges(edge))
116                                 for edge in variable_graph.get_edges(var_id)], []), variable_graph.get_edges(var_id)
117                                 )
118                         )
119                         for var_id in var_ids]
120                 )
121                 #map var id to callbacks
122                 var_id2cbs = dict(
123                         [(var_id, filter(lambda c: var_id in expr_utils.expr_split(c), callbacks))
124                         for var_id in var_ids]
125                 )
126                 #load the namespace
127                 namespace = {
128                         'imports': imports,
129                         'flow_graph': self._flow_graph,
130                         'variables': variables,
131                         'controls': controls,
132                         'parameters': parameters,
133                         'blocks': blocks,
134                         'connections': connections,
135                         'generate_options': self._generate_options,
136                         'var_id2expr': var_id2expr,
137                         'var_id2deps': var_id2deps,
138                         'var_id2cbs': var_id2cbs,
139                 }
140                 #build the template
141                 t = Template(open(FLOW_GRAPH_TEMPLATE, 'r').read(), namespace)
142                 return str(t)