summaryrefslogtreecommitdiff
path: root/grc/core/utils
diff options
context:
space:
mode:
Diffstat (limited to 'grc/core/utils')
-rw-r--r--grc/core/utils/__init__.py10
-rw-r--r--grc/core/utils/_complexity.py (renamed from grc/core/utils/complexity.py)15
-rw-r--r--grc/core/utils/epy_block_io.py11
-rw-r--r--grc/core/utils/expr_utils.py20
-rw-r--r--grc/core/utils/extract_docs.py28
-rw-r--r--grc/core/utils/odict.py115
6 files changed, 51 insertions, 148 deletions
diff --git a/grc/core/utils/__init__.py b/grc/core/utils/__init__.py
index 6b23da2723..d095179a10 100644
--- a/grc/core/utils/__init__.py
+++ b/grc/core/utils/__init__.py
@@ -15,8 +15,10 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
-import expr_utils
-import epy_block_io
-import extract_docs
+from __future__ import absolute_import
-from odict import odict
+from . import expr_utils
+from . import epy_block_io
+from . import extract_docs
+
+from ._complexity import calculate_flowgraph_complexity
diff --git a/grc/core/utils/complexity.py b/grc/core/utils/_complexity.py
index baa8040db4..c0f3ae9de4 100644
--- a/grc/core/utils/complexity.py
+++ b/grc/core/utils/_complexity.py
@@ -4,12 +4,12 @@ def calculate_flowgraph_complexity(flowgraph):
dbal = 0
for block in flowgraph.blocks:
# Skip options block
- if block.get_key() == 'options':
+ if block.key == 'options':
continue
# Don't worry about optional sinks?
- sink_list = filter(lambda c: not c.get_optional(), block.get_sinks())
- source_list = filter(lambda c: not c.get_optional(), block.get_sources())
+ sink_list = [c for c in block.sinks if not c.get_optional()]
+ source_list = [c for c in block.sources if not c.get_optional()]
sinks = float(len(sink_list))
sources = float(len(source_list))
base = max(min(sinks, sources), 1)
@@ -22,14 +22,15 @@ def calculate_flowgraph_complexity(flowgraph):
multi = 1
# Connection ratio multiplier
- sink_multi = max(float(sum(map(lambda c: len(c.get_connections()), sink_list)) / max(sinks, 1.0)), 1.0)
- source_multi = max(float(sum(map(lambda c: len(c.get_connections()), source_list)) / max(sources, 1.0)), 1.0)
- dbal = dbal + (base * multi * sink_multi * source_multi)
+ sink_multi = max(float(sum(len(c.get_connections()) for c in sink_list) / max(sinks, 1.0)), 1.0)
+ source_multi = max(float(sum(len(c.get_connections()) for c in source_list) / max(sources, 1.0)), 1.0)
+ dbal += base * multi * sink_multi * source_multi
blocks = float(len(flowgraph.blocks))
connections = float(len(flowgraph.connections))
elements = blocks + connections
- disabled_connections = len(filter(lambda c: not c.get_enabled(), flowgraph.connections))
+ disabled_connections = sum(not c.enabled for c in flowgraph.connections)
+
variables = elements - blocks - connections
enabled = float(len(flowgraph.get_enabled_blocks()))
diff --git a/grc/core/utils/epy_block_io.py b/grc/core/utils/epy_block_io.py
index a094ab7ad5..823116adb9 100644
--- a/grc/core/utils/epy_block_io.py
+++ b/grc/core/utils/epy_block_io.py
@@ -1,7 +1,12 @@
+from __future__ import absolute_import
+
import inspect
import collections
+import six
+from six.moves import zip
+
TYPE_MAP = {
'complex64': 'complex', 'complex': 'complex',
@@ -32,10 +37,10 @@ def _ports(sigs, msgs):
def _find_block_class(source_code, cls):
ns = {}
try:
- exec source_code in ns
+ exec(source_code, ns)
except Exception as e:
raise ValueError("Can't interpret source code: " + str(e))
- for var in ns.itervalues():
+ for var in six.itervalues(ns):
if inspect.isclass(var) and issubclass(var, cls):
return var
raise ValueError('No python block class found in code')
@@ -53,7 +58,7 @@ def extract(cls):
spec = inspect.getargspec(cls.__init__)
init_args = spec.args[1:]
- defaults = map(repr, spec.defaults or ())
+ defaults = [repr(arg) for arg in (spec.defaults or ())]
doc = cls.__doc__ or cls.__init__.__doc__ or ''
cls_name = cls.__name__
diff --git a/grc/core/utils/expr_utils.py b/grc/core/utils/expr_utils.py
index 2059ceff9f..555bd709b1 100644
--- a/grc/core/utils/expr_utils.py
+++ b/grc/core/utils/expr_utils.py
@@ -17,7 +17,12 @@ along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
+from __future__ import absolute_import, print_function
+
import string
+
+import six
+
VAR_CHARS = string.letters + string.digits + '_'
@@ -50,7 +55,7 @@ class graph(object):
self._graph[src_node_key].remove(dest_node_key)
def get_nodes(self):
- return self._graph.keys()
+ return list(self._graph.keys())
def get_edges(self, node_key):
return self._graph[node_key]
@@ -85,7 +90,7 @@ def expr_split(expr, var_chars=VAR_CHARS):
toks.append(char)
tok = ''
toks.append(tok)
- return filter(lambda t: t, toks)
+ return [t for t in toks if t]
def expr_replace(expr, replace_dict):
@@ -101,7 +106,7 @@ def expr_replace(expr, replace_dict):
"""
expr_splits = expr_split(expr, var_chars=VAR_CHARS + '.')
for i, es in enumerate(expr_splits):
- if es in replace_dict.keys():
+ if es in list(replace_dict.keys()):
expr_splits[i] = replace_dict[es]
return ''.join(expr_splits)
@@ -118,7 +123,7 @@ def get_variable_dependencies(expr, vars):
a subset of vars used in the expression
"""
expr_toks = expr_split(expr)
- return set(var for var in vars if var in expr_toks)
+ return set(v for v in vars if v in expr_toks)
def get_graph(exprs):
@@ -131,12 +136,12 @@ def get_graph(exprs):
Returns:
a graph of variable deps
"""
- vars = exprs.keys()
+ vars = list(exprs.keys())
# Get dependencies for each expression, load into graph
var_graph = graph()
for var in vars:
var_graph.add_node(var)
- for var, expr in exprs.iteritems():
+ for var, expr in six.iteritems(exprs):
for dep in get_variable_dependencies(expr, vars):
if dep != var:
var_graph.add_edge(dep, var)
@@ -159,7 +164,7 @@ def sort_variables(exprs):
# Determine dependency order
while var_graph.get_nodes():
# Get a list of nodes with no edges
- indep_vars = filter(lambda var: not var_graph.get_edges(var), var_graph.get_nodes())
+ indep_vars = [var for var in var_graph.get_nodes() if not var_graph.get_edges(var)]
if not indep_vars:
raise Exception('circular dependency caught in sort_variables')
# Add the indep vars to the end of the list
@@ -189,3 +194,4 @@ def sort_objects(objects, get_id, get_expr):
sorted_ids = sort_variables(id2expr)
# Return list of sorted objects
return [id2obj[id] for id in sorted_ids]
+
diff --git a/grc/core/utils/extract_docs.py b/grc/core/utils/extract_docs.py
index a6e0bc971e..cff8a81099 100644
--- a/grc/core/utils/extract_docs.py
+++ b/grc/core/utils/extract_docs.py
@@ -17,15 +17,19 @@ along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
+from __future__ import absolute_import, print_function
+
import sys
import re
import subprocess
import threading
import json
-import Queue
import random
import itertools
+import six
+from six.moves import queue, filter, range
+
###############################################################################
# The docstring extraction
@@ -124,7 +128,7 @@ class SubprocessLoader(object):
self.callback_query_result = callback_query_result
self.callback_finished = callback_finished or (lambda: None)
- self._queue = Queue.Queue()
+ self._queue = queue.Queue()
self._thread = None
self._worker = None
self._shutdown = threading.Event()
@@ -157,14 +161,14 @@ class SubprocessLoader(object):
cmd, args = self._last_cmd
if cmd == 'query':
msg += " (crashed while loading {0!r})".format(args[0])
- print >> sys.stderr, msg
+ print(msg, file=sys.stderr)
continue # restart
else:
break # normal termination, return
finally:
self._worker.terminate()
else:
- print >> sys.stderr, "Warning: docstring loader crashed too often"
+ print("Warning: docstring loader crashed too often", file=sys.stderr)
self._thread = None
self._worker = None
self.callback_finished()
@@ -203,9 +207,9 @@ class SubprocessLoader(object):
key, docs = args
self.callback_query_result(key, docs)
elif cmd == 'error':
- print args
+ print(args)
else:
- print >> sys.stderr, "Unknown response:", cmd, args
+ print("Unknown response:", cmd, args, file=sys.stderr)
def query(self, key, imports=None, make=None):
""" Request docstring extraction for a certain key """
@@ -270,12 +274,12 @@ if __name__ == '__worker__':
elif __name__ == '__main__':
def callback(key, docs):
- print key
- for match, doc in docs.iteritems():
- print '-->', match
- print doc.strip()
- print
- print
+ print(key)
+ for match, doc in six.iteritems(docs):
+ print('-->', match)
+ print(doc.strip())
+ print()
+ print()
r = SubprocessLoader(callback)
diff --git a/grc/core/utils/odict.py b/grc/core/utils/odict.py
deleted file mode 100644
index 85927e869f..0000000000
--- a/grc/core/utils/odict.py
+++ /dev/null
@@ -1,115 +0,0 @@
-"""
-Copyright 2008-2015 Free Software Foundation, Inc.
-This file is part of GNU Radio
-
-GNU Radio Companion is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-GNU Radio Companion is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
-"""
-
-from UserDict import DictMixin
-
-
-class odict(DictMixin):
-
- def __init__(self, d={}):
- self._keys = list(d.keys())
- self._data = dict(d.copy())
-
- def __setitem__(self, key, value):
- if key not in self._data:
- self._keys.append(key)
- self._data[key] = value
-
- def __getitem__(self, key):
- return self._data[key]
-
- def __delitem__(self, key):
- del self._data[key]
- self._keys.remove(key)
-
- def keys(self):
- return list(self._keys)
-
- def copy(self):
- copy_dict = odict()
- copy_dict._data = self._data.copy()
- copy_dict._keys = list(self._keys)
- return copy_dict
-
- def insert_after(self, pos_key, key, val):
- """
- Insert the new key, value entry after the entry given by the position key.
- If the positional key is None, insert at the end.
-
- Args:
- pos_key: the positional key
- key: the key for the new entry
- val: the value for the new entry
- """
- index = (pos_key is None) and len(self._keys) or self._keys.index(pos_key)
- if key in self._keys:
- raise KeyError('Cannot insert, key "{}" already exists'.format(str(key)))
- self._keys.insert(index+1, key)
- self._data[key] = val
-
- def insert_before(self, pos_key, key, val):
- """
- Insert the new key, value entry before the entry given by the position key.
- If the positional key is None, insert at the begining.
-
- Args:
- pos_key: the positional key
- key: the key for the new entry
- val: the value for the new entry
- """
- index = (pos_key is not None) and self._keys.index(pos_key) or 0
- if key in self._keys:
- raise KeyError('Cannot insert, key "{}" already exists'.format(str(key)))
- self._keys.insert(index, key)
- self._data[key] = val
-
- def find(self, key):
- """
- Get the value for this key if exists.
-
- Args:
- key: the key to search for
-
- Returns:
- the value or None
- """
- if key in self:
- return self[key]
- return None
-
- def findall(self, key):
- """
- Get a list of values for this key.
-
- Args:
- key: the key to search for
-
- Returns:
- a list of values or empty list
- """
- obj = self.find(key)
- if obj is None:
- obj = list()
- if isinstance(obj, list):
- return obj
- return [obj]
-
- def clear(self):
- self._data.clear()
- del self._keys[:] \ No newline at end of file