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