Merged r9481:9518 on jblum/grc_reorganize into trunk. Reorganized grc source under...
[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
30 class Generator(object):
31
32         def __init__(self, flow_graph, file_path):
33                 """
34                 Initialize the generator object.
35                 Determine the file to generate.
36                 @param flow_graph the flow graph object
37                 @param file_path the path to write the file to
38                 """
39                 self._flow_graph = flow_graph
40                 self._generate_options = self._flow_graph.get_option('generate_options')
41                 if self._generate_options == 'hb':
42                         self._mode = HIER_BLOCK_FILE_MODE
43                         dirname = HIER_BLOCKS_LIB_DIR
44                 else:
45                         self._mode = TOP_BLOCK_FILE_MODE
46                         dirname = os.path.dirname(file_path)
47                 filename = self._flow_graph.get_option('id') + '.py'
48                 self._file_path = os.path.join(dirname, filename)
49
50         def get_file_path(self): return self._file_path
51
52         def write(self):
53                 #generate
54                 open(self.get_file_path(), 'w').write(str(self))
55                 if self._generate_options == 'hb':
56                         #convert hier block to xml wrapper
57                         convert_hier.convert_hier(self._flow_graph, self.get_file_path())
58                 os.chmod(self.get_file_path(), self._mode)
59
60         def get_popen(self):
61                 """
62                 Execute this python flow graph.
63                 @return a popen object
64                 """
65                 #execute
66                 cmds = [PYEXEC, self.get_file_path()]
67                 if self._generate_options == 'no_gui':
68                         cmds = ['xterm', '-e'] + cmds
69                 p = subprocess.Popen(args=cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, universal_newlines=True)
70                 return p
71
72         def __str__(self):
73                 """
74                 Convert the flow graph to python code.
75                 @return a string of python code
76                 """
77                 imports = self._flow_graph.get_imports()
78                 variables = self._flow_graph.get_variables()
79                 parameters = self._flow_graph.get_parameters()
80                 #list of variables with controls
81                 controls = filter(lambda v: v.get_key().startswith('variable_'), variables)
82                 #list of blocks not including variables and imports and parameters and disabled
83                 blocks = sorted(self._flow_graph.get_enabled_blocks(), lambda x, y: cmp(x.get_id(), y.get_id()))
84                 blocks = filter(lambda b: b not in (imports + parameters + variables), blocks)
85                 #list of connections where each endpoint is enabled
86                 connections = self._flow_graph.get_enabled_connections()
87                 #list of variable names
88                 var_ids = [var.get_id() for var in parameters + variables]
89                 #list of callbacks (prepend self.)
90                 callbacks = [
91                         expr_utils.expr_prepend(cb, var_ids, 'self.')
92                         for cb in sum([block.get_callbacks() for block in self._flow_graph.get_blocks()], [])
93                 ]
94                 #map var id to the expression (prepend self.)
95                 var_id2expr = dict(
96                         [(var.get_id(), expr_utils.expr_prepend(var.get_make().split('\n')[0], var_ids, 'self.'))
97                         for var in parameters + variables]
98                 )
99                 #create graph structure for variables
100                 variable_graph = expr_utils.get_graph(var_id2expr)
101                 #map var id to direct dependents
102                 #for each var id, make a list of all 2nd order edges
103                 #use all edges of that id that are not also 2nd order edges
104                 #meaning: list variables the ONLY depend directly on this variable
105                 #and not variables that also depend indirectly on this variable
106                 var_id2deps = dict(
107                         [(var_id, filter(lambda e: e not in sum([list(variable_graph.get_edges(edge))
108                                 for edge in variable_graph.get_edges(var_id)], []), variable_graph.get_edges(var_id)
109                                 )
110                         )
111                         for var_id in var_ids]
112                 )
113                 #map var id to callbacks
114                 var_id2cbs = dict(
115                         [(var_id, filter(lambda c: var_id in expr_utils.expr_split(c), callbacks))
116                         for var_id in var_ids]
117                 )
118                 #load the namespace
119                 namespace = {
120                         'imports': imports,
121                         'flow_graph': self._flow_graph,
122                         'variables': variables,
123                         'controls': controls,
124                         'parameters': parameters,
125                         'blocks': blocks,
126                         'connections': connections,
127                         'generate_options': self._generate_options,
128                         'var_id2expr': var_id2expr,
129                         'var_id2deps': var_id2deps,
130                         'var_id2cbs': var_id2cbs,
131                 }
132                 #build the template
133                 t = Template(open(FLOW_GRAPH_TEMPLATE, 'r').read(), namespace)
134                 return str(t)