summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJarrod Millman <jarrod.millman@gmail.com>2017-09-10 00:44:51 -0700
committerGitHub <noreply@github.com>2017-09-10 00:44:51 -0700
commit06c701e3a4c598ec88c799d325de541e47af042c (patch)
treed57c2ec2cee9248583615bc08976b67faeb12e43
parentef82a6b15e1475eb587caf18d582b4d37ba20327 (diff)
parent27ed9f0a5444a76f2db26f998d62a17a225ecae0 (diff)
downloadnetworkx-06c701e3a4c598ec88c799d325de541e47af042c.tar.gz
Merge pull request #2659 from jarrodmillman/mpl2.1-deprecated
matplotlib 2.1 deprecated is_string_like
-rw-r--r--networkx/algorithms/isomorphism/matchhelpers.py51
-rw-r--r--networkx/algorithms/operators/all.py4
-rw-r--r--networkx/algorithms/operators/binary.py4
-rw-r--r--networkx/drawing/nx_pylab.py21
-rw-r--r--networkx/readwrite/leda.py54
-rw-r--r--networkx/readwrite/p2g.py45
-rw-r--r--networkx/readwrite/pajek.py6
-rw-r--r--networkx/utils/decorators.py23
-rw-r--r--networkx/utils/misc.py46
9 files changed, 148 insertions, 106 deletions
diff --git a/networkx/algorithms/isomorphism/matchhelpers.py b/networkx/algorithms/isomorphism/matchhelpers.py
index 83f3ad57..dc20a43f 100644
--- a/networkx/algorithms/isomorphism/matchhelpers.py
+++ b/networkx/algorithms/isomorphism/matchhelpers.py
@@ -14,7 +14,7 @@ __all__ = ['categorical_node_match',
'generic_node_match',
'generic_edge_match',
'generic_multiedge_match',
- ]
+ ]
def copyfunc(f, name=None):
@@ -30,6 +30,7 @@ def copyfunc(f, name=None):
name or f.__name__, f.__defaults__,
f.__closure__)
+
def allclose(x, y, rtol=1.0000000000000001e-05, atol=1e-08):
"""Returns True if x and y are sufficiently close, elementwise.
@@ -42,8 +43,8 @@ def allclose(x, y, rtol=1.0000000000000001e-05, atol=1e-08):
"""
# assume finite weights, see numpy.allclose() for reference
- for xi, yi in zip(x,y):
- if not ( abs(xi-yi) <= atol + rtol * abs(yi) ):
+ for xi, yi in zip(x, y):
+ if not (abs(xi - yi) <= atol + rtol * abs(yi)):
return False
return True
@@ -60,7 +61,7 @@ def close(x, y, rtol=1.0000000000000001e-05, atol=1e-08):
"""
# assume finite weights, see numpy.allclose() for reference
- return abs(x-y) <= atol + rtol * abs(y)
+ return abs(x - y) <= atol + rtol * abs(y)
categorical_doc = """
@@ -92,17 +93,19 @@ Examples
"""
+
def categorical_node_match(attr, default):
if nx.utils.is_string_like(attr):
def match(data1, data2):
return data1.get(attr, default) == data2.get(attr, default)
else:
- attrs = list(zip(attr, default)) # Python 3
+ attrs = list(zip(attr, default)) # Python 3
def match(data1, data2):
return all(data1.get(attr, d) == data2.get(attr, d) for attr, d in attrs)
return match
+
try:
categorical_edge_match = copyfunc(categorical_node_match, 'categorical_edge_match')
except NotImplementedError:
@@ -112,6 +115,7 @@ except NotImplementedError:
def categorical_edge_match(*args, **kwargs):
return categorical_node_match(*args, **kwargs)
+
def categorical_multiedge_match(attr, default):
if nx.utils.is_string_like(attr):
def match(datasets1, datasets2):
@@ -119,19 +123,21 @@ def categorical_multiedge_match(attr, default):
values2 = set([data.get(attr, default) for data in datasets2.values()])
return values1 == values2
else:
- attrs = list(zip(attr, default)) # Python 3
+ attrs = list(zip(attr, default)) # Python 3
+
def match(datasets1, datasets2):
values1 = set([])
for data1 in datasets1.values():
- x = tuple( data1.get(attr, d) for attr, d in attrs )
+ x = tuple(data1.get(attr, d) for attr, d in attrs)
values1.add(x)
values2 = set([])
for data2 in datasets2.values():
- x = tuple( data2.get(attr, d) for attr, d in attrs )
+ x = tuple(data2.get(attr, d) for attr, d in attrs)
values2.add(x)
return values1 == values2
return match
+
# Docstrings for categorical functions.
categorical_node_match.__doc__ = categorical_doc
categorical_edge_match.__doc__ = categorical_doc.replace('node', 'edge')
@@ -173,6 +179,7 @@ Examples
"""
+
def numerical_node_match(attr, default, rtol=1.0000000000000001e-05, atol=1e-08):
if nx.utils.is_string_like(attr):
def match(data1, data2):
@@ -180,13 +187,15 @@ def numerical_node_match(attr, default, rtol=1.0000000000000001e-05, atol=1e-08)
data2.get(attr, default),
rtol=rtol, atol=atol)
else:
- attrs = list(zip(attr, default)) # Python 3
+ attrs = list(zip(attr, default)) # Python 3
+
def match(data1, data2):
values1 = [data1.get(attr, d) for attr, d in attrs]
values2 = [data2.get(attr, d) for attr, d in attrs]
return allclose(values1, values2, rtol=rtol, atol=atol)
return match
+
try:
numerical_edge_match = copyfunc(numerical_node_match, 'numerical_edge_match')
except NotImplementedError:
@@ -196,6 +205,7 @@ except NotImplementedError:
def numerical_edge_match(*args, **kwargs):
return numerical_node_match(*args, **kwargs)
+
def numerical_multiedge_match(attr, default, rtol=1.0000000000000001e-05, atol=1e-08):
if nx.utils.is_string_like(attr):
def match(datasets1, datasets2):
@@ -204,14 +214,15 @@ def numerical_multiedge_match(attr, default, rtol=1.0000000000000001e-05, atol=1
return allclose(values1, values2, rtol=rtol, atol=atol)
else:
attrs = list(zip(attr, default)) # Python 3
+
def match(datasets1, datasets2):
values1 = []
for data1 in datasets1.values():
- x = tuple( data1.get(attr, d) for attr, d in attrs )
+ x = tuple(data1.get(attr, d) for attr, d in attrs)
values1.append(x)
values2 = []
for data2 in datasets2.values():
- x = tuple( data2.get(attr, d) for attr, d in attrs )
+ x = tuple(data2.get(attr, d) for attr, d in attrs)
values2.append(x)
values1.sort()
values2.sort()
@@ -222,6 +233,7 @@ def numerical_multiedge_match(attr, default, rtol=1.0000000000000001e-05, atol=1
return True
return match
+
# Docstrings for numerical functions.
numerical_node_match.__doc__ = numerical_doc
numerical_edge_match.__doc__ = numerical_doc.replace('node', 'edge')
@@ -265,12 +277,14 @@ Examples
"""
+
def generic_node_match(attr, default, op):
if nx.utils.is_string_like(attr):
def match(data1, data2):
return op(data1.get(attr, default), data2.get(attr, default))
else:
- attrs = list(zip(attr, default, op)) # Python 3
+ attrs = list(zip(attr, default, op)) # Python 3
+
def match(data1, data2):
for attr, d, operator in attrs:
if not operator(data1.get(attr, d), data2.get(attr, d)):
@@ -279,6 +293,7 @@ def generic_node_match(attr, default, op):
return True
return match
+
try:
generic_edge_match = copyfunc(generic_node_match, 'generic_edge_match')
except NotImplementedError:
@@ -288,6 +303,7 @@ except NotImplementedError:
def generic_edge_match(*args, **kwargs):
return generic_node_match(*args, **kwargs)
+
def generic_multiedge_match(attr, default, op):
"""Returns a comparison function for a generic attribute.
@@ -334,19 +350,20 @@ def generic_multiedge_match(attr, default, op):
attr = [attr]
default = [default]
op = [op]
- attrs = list(zip(attr, default)) # Python 3
+ attrs = list(zip(attr, default)) # Python 3
+
def match(datasets1, datasets2):
values1 = []
for data1 in datasets1.values():
- x = tuple( data1.get(attr, d) for attr, d in attrs )
+ x = tuple(data1.get(attr, d) for attr, d in attrs)
values1.append(x)
values2 = []
for data2 in datasets2.values():
- x = tuple( data2.get(attr, d) for attr, d in attrs )
+ x = tuple(data2.get(attr, d) for attr, d in attrs)
values2.append(x)
for vals2 in permutations(values2):
for xi, yi in zip(values1, vals2):
- if not all(map(lambda x,y,z: z(x,y), xi, yi, op)):
+ if not all(map(lambda x, y, z: z(x, y), xi, yi, op)):
# This is not an isomorphism, go to next permutation.
break
else:
@@ -357,7 +374,7 @@ def generic_multiedge_match(attr, default, op):
return False
return match
+
# Docstrings for numerical functions.
generic_node_match.__doc__ = generic_doc
generic_edge_match.__doc__ = generic_doc.replace('node', 'edge')
-
diff --git a/networkx/algorithms/operators/all.py b/networkx/algorithms/operators/all.py
index 6c2b60fa..f37cb40c 100644
--- a/networkx/algorithms/operators/all.py
+++ b/networkx/algorithms/operators/all.py
@@ -13,8 +13,8 @@ except ImportError: # Python3 has zip_longest
import networkx as nx
# from networkx.utils import is_string_like
-__author__ = """\n""".join([ 'Robert King <kingrobertking@gmail.com>',
- 'Aric Hagberg <aric.hagberg@gmail.com>'])
+__author__ = """\n""".join(['Robert King <kingrobertking@gmail.com>',
+ 'Aric Hagberg <aric.hagberg@gmail.com>'])
__all__ = ['union_all', 'compose_all', 'disjoint_union_all',
'intersection_all']
diff --git a/networkx/algorithms/operators/binary.py b/networkx/algorithms/operators/binary.py
index 3e7b0545..470f54e6 100644
--- a/networkx/algorithms/operators/binary.py
+++ b/networkx/algorithms/operators/binary.py
@@ -10,8 +10,8 @@ Operations on graphs including union, intersection, difference.
import networkx as nx
from networkx.utils import is_string_like
__author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>',
- 'Pieter Swart (swart@lanl.gov)',
- 'Dan Schult(dschult@colgate.edu)'])
+ 'Pieter Swart (swart@lanl.gov)',
+ 'Dan Schult(dschult@colgate.edu)'])
__all__ = ['union', 'compose', 'disjoint_union', 'intersection',
'difference', 'symmetric_difference']
diff --git a/networkx/drawing/nx_pylab.py b/networkx/drawing/nx_pylab.py
index 79dc5ed5..5832b9a7 100644
--- a/networkx/drawing/nx_pylab.py
+++ b/networkx/drawing/nx_pylab.py
@@ -39,6 +39,13 @@ __all__ = ['draw',
'draw_spring',
'draw_shell']
+# 2.x/3.x compatibility
+try:
+ basestring
+except NameError:
+ basestring = str
+ unicode = str
+
def draw(G, pos=None, ax=None, **kwds):
"""Draw the graph G with Matplotlib.
@@ -519,17 +526,15 @@ def draw_networkx_edges(G, pos,
else:
lw = width
- if not cb.is_string_like(edge_color) \
+ if not isinstance(edge_color, basestring) \
and cb.iterable(edge_color) \
and len(edge_color) == len(edge_pos):
- if np.alltrue([cb.is_string_like(c)
- for c in edge_color]):
+ if np.alltrue([isinstance(c, basestring) for c in edge_color]):
# (should check ALL elements)
# list of color letters such as ['k','r','k',...]
edge_colors = tuple([colorConverter.to_rgba(c, alpha)
for c in edge_color])
- elif np.alltrue([not cb.is_string_like(c)
- for c in edge_color]):
+ elif np.alltrue([not isinstance(c, basestring) for c in edge_color]):
# If color specs are given as (rgb) or (rgba) tuples, we're OK
if np.alltrue([cb.iterable(c) and len(c) in (3, 4)
for c in edge_color]):
@@ -540,7 +545,7 @@ def draw_networkx_edges(G, pos,
else:
raise ValueError('edge_color must consist of either color names or numbers')
else:
- if cb.is_string_like(edge_color) or len(edge_color) == 1:
+ if isinstance(edge_color, basestring) or len(edge_color) == 1:
edge_colors = (colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError(
@@ -721,7 +726,7 @@ def draw_networkx_labels(G, pos,
text_items = {} # there is no text collection so we'll fake one
for n, label in labels.items():
(x, y) = pos[n]
- if not cb.is_string_like(label):
+ if not isinstance(label, basestring):
label = str(label) # this will cause "1" and 1 to be labeled the same
t = ax.text(x, y,
label,
@@ -859,7 +864,7 @@ def draw_networkx_edge_labels(G, pos,
ec=(1.0, 1.0, 1.0),
fc=(1.0, 1.0, 1.0),
)
- if not cb.is_string_like(label):
+ if not isinstance(label, basestring):
label = str(label) # this will cause "1" and 1 to be labeled the same
# set optional alignment
diff --git a/networkx/readwrite/leda.py b/networkx/readwrite/leda.py
index 71c3c2c0..b96a590f 100644
--- a/networkx/readwrite/leda.py
+++ b/networkx/readwrite/leda.py
@@ -20,11 +20,12 @@ __author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__all__ = ['read_leda', 'parse_leda']
-import networkx as nx
+import networkx as nx
from networkx.exception import NetworkXError
from networkx.utils import open_file, is_string_like
-@open_file(0,mode='rb')
+
+@open_file(0, mode='rb')
def read_leda(path, encoding='UTF-8'):
"""Read graph in LEDA format from path.
@@ -41,13 +42,13 @@ def read_leda(path, encoding='UTF-8'):
Examples
--------
G=nx.read_leda('file.leda')
-
+
References
----------
.. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
"""
- lines=(line.decode(encoding) for line in path)
- G=parse_leda(lines)
+ lines = (line.decode(encoding) for line in path)
+ G = parse_leda(lines)
return G
@@ -66,41 +67,42 @@ def parse_leda(lines):
Examples
--------
G=nx.parse_leda(string)
-
+
References
----------
.. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
"""
- if is_string_like(lines): lines=iter(lines.split('\n'))
- lines = iter([line.rstrip('\n') for line in lines \
- if not (line.startswith('#') or line.startswith('\n') or line=='')])
+ if is_string_like(lines):
+ lines = iter(lines.split('\n'))
+ lines = iter([line.rstrip('\n') for line in lines
+ if not (line.startswith('#') or line.startswith('\n') or line == '')])
for i in range(3):
next(lines)
# Graph
- du = int(next(lines)) # -1=directed, -2=undirected
- if du==-1:
+ du = int(next(lines)) # -1=directed, -2=undirected
+ if du == -1:
G = nx.DiGraph()
else:
G = nx.Graph()
-
+
# Nodes
- n =int(next(lines)) # number of nodes
- node={}
- for i in range(1,n+1): # LEDA counts from 1 to n
- symbol=next(lines).rstrip().strip('|{}| ')
- if symbol=="": symbol=str(i) # use int if no label - could be trouble
- node[i]=symbol
-
- G.add_nodes_from([s for i,s in node.items()])
-
+ n = int(next(lines)) # number of nodes
+ node = {}
+ for i in range(1, n + 1): # LEDA counts from 1 to n
+ symbol = next(lines).rstrip().strip('|{}| ')
+ if symbol == "":
+ symbol = str(i) # use int if no label - could be trouble
+ node[i] = symbol
+
+ G.add_nodes_from([s for i, s in node.items()])
+
# Edges
- m = int(next(lines)) # number of edges
+ m = int(next(lines)) # number of edges
for i in range(m):
try:
- s,t,reversal,label=next(lines).split()
+ s, t, reversal, label = next(lines).split()
except:
- raise NetworkXError('Too few fields in LEDA.GRAPH edge %d'%(i+1))
+ raise NetworkXError('Too few fields in LEDA.GRAPH edge %d' % (i + 1))
# BEWARE: no handling of reversal edges
- G.add_edge(node[int(s)],node[int(t)],label=label[2:-2])
+ G.add_edge(node[int(s)], node[int(t)], label=label[2:-2])
return G
-
diff --git a/networkx/readwrite/p2g.py b/networkx/readwrite/p2g.py
index a0096763..910a6dd5 100644
--- a/networkx/readwrite/p2g.py
+++ b/networkx/readwrite/p2g.py
@@ -31,19 +31,20 @@ edges. Observe that node labeled "c" has an outgoing edge to
itself. Indeed, self-loops are allowed. Node index starts from 0.
"""
-# Copyright (C) 2008-2012 by
+# Copyright (C) 2008-2012 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import networkx
-from networkx.utils import is_string_like,open_file
+from networkx.utils import is_string_like, open_file
__author__ = '\n'.join(['Willem Ligtenberg (w.p.a.ligtenberg@tue.nl)',
- 'Aric Hagberg (aric.hagberg@gmail.com)'])
+ 'Aric Hagberg (aric.hagberg@gmail.com)'])
-@open_file(1,mode='w')
-def write_p2g(G, path, encoding = 'utf-8'):
+
+@open_file(1, mode='w')
+def write_p2g(G, path, encoding='utf-8'):
"""Write NetworkX graph in p2g format.
Notes
@@ -51,18 +52,19 @@ def write_p2g(G, path, encoding = 'utf-8'):
This format is meant to be used with directed graphs with
possible self loops.
"""
- path.write(("%s\n"%G.name).encode(encoding))
- path.write(("%s %s\n"%(G.order(),G.size())).encode(encoding))
+ path.write(("%s\n" % G.name).encode(encoding))
+ path.write(("%s %s\n" % (G.order(), G.size())).encode(encoding))
nodes = list(G)
# make dictionary mapping nodes to integers
- nodenumber=dict(zip(nodes,range(len(nodes))))
+ nodenumber = dict(zip(nodes, range(len(nodes))))
for n in nodes:
- path.write(("%s\n"%n).encode(encoding))
+ path.write(("%s\n" % n).encode(encoding))
for nbr in G.neighbors(n):
- path.write(("%s "%nodenumber[nbr]).encode(encoding))
+ path.write(("%s " % nodenumber[nbr]).encode(encoding))
path.write("\n".encode(encoding))
-@open_file(0,mode='r')
+
+@open_file(0, mode='r')
def read_p2g(path, encoding='utf-8'):
"""Read graph in p2g format from path.
@@ -76,9 +78,10 @@ def read_p2g(path, encoding='utf-8'):
use D=networkx.DiGraph(read_p2g(path))
"""
lines = (line.decode(encoding) for line in path)
- G=parse_p2g(lines)
+ G = parse_p2g(lines)
return G
+
def parse_p2g(lines):
"""Parse p2g format graph from string or iterable.
@@ -88,20 +91,20 @@ def parse_p2g(lines):
"""
description = next(lines).strip()
# are multiedges (parallel edges) allowed?
- G=networkx.MultiDiGraph(name=description,selfloops=True)
- nnodes,nedges=map(int,next(lines).split())
- nodelabel={}
- nbrs={}
+ G = networkx.MultiDiGraph(name=description, selfloops=True)
+ nnodes, nedges = map(int, next(lines).split())
+ nodelabel = {}
+ nbrs = {}
# loop over the nodes keeping track of node labels and out neighbors
# defer adding edges until all node labels are known
for i in range(nnodes):
- n=next(lines).strip()
- nodelabel[i]=n
+ n = next(lines).strip()
+ nodelabel[i] = n
G.add_node(n)
- nbrs[n]=map(int,next(lines).split())
+ nbrs[n] = map(int, next(lines).split())
# now we know all of the node labels so we can add the edges
- # with the correct labels
+ # with the correct labels
for n in G:
for nbr in nbrs[n]:
- G.add_edge(n,nodelabel[nbr])
+ G.add_edge(n, nodelabel[nbr])
return G
diff --git a/networkx/readwrite/pajek.py b/networkx/readwrite/pajek.py
index 8acc3276..f75aaa8b 100644
--- a/networkx/readwrite/pajek.py
+++ b/networkx/readwrite/pajek.py
@@ -165,7 +165,7 @@ def parse_pajek(lines):
lines = iter(lines.split('\n'))
lines = iter([line.rstrip('\n') for line in lines])
G = nx.MultiDiGraph() # are multiedges allowed in Pajek? assume yes
- labels = [] # in the order of the file, needed for matrix
+ labels = [] # in the order of the file, needed for matrix
while lines:
try:
l = next(lines)
@@ -197,8 +197,8 @@ def parse_pajek(lines):
try:
x, y, shape = splitline[2:5]
G.nodes[label].update({'x': float(x),
- 'y': float(y),
- 'shape': shape})
+ 'y': float(y),
+ 'shape': shape})
except:
pass
extra_attr = zip(splitline[5::2], splitline[6::2])
diff --git a/networkx/utils/decorators.py b/networkx/utils/decorators.py
index f88c6711..00cfcff2 100644
--- a/networkx/utils/decorators.py
+++ b/networkx/utils/decorators.py
@@ -13,6 +13,7 @@ __all__ = [
'nodes_or_number',
]
+
def not_implemented_for(*graph_types):
"""Decorator to mark algorithms as not implemented
@@ -49,12 +50,12 @@ def not_implemented_for(*graph_types):
pass
"""
@decorator
- def _not_implemented_for(f,*args,**kwargs):
+ def _not_implemented_for(f, *args, **kwargs):
graph = args[0]
- terms= {'directed':graph.is_directed(),
- 'undirected':not graph.is_directed(),
- 'multigraph':graph.is_multigraph(),
- 'graph':not graph.is_multigraph()}
+ terms = {'directed': graph.is_directed(),
+ 'undirected': not graph.is_directed(),
+ 'multigraph': graph.is_multigraph(),
+ 'graph': not graph.is_multigraph()}
match = True
try:
for t in graph_types:
@@ -63,24 +64,26 @@ def not_implemented_for(*graph_types):
raise KeyError('use one or more of ',
'directed, undirected, multigraph, graph')
if match:
- raise nx.NetworkXNotImplemented('not implemented for %s type'%
+ raise nx.NetworkXNotImplemented('not implemented for %s type' %
' '.join(graph_types))
else:
- return f(*args,**kwargs)
+ return f(*args, **kwargs)
return _not_implemented_for
def _open_gz(path, mode):
import gzip
- return gzip.open(path,mode=mode)
+ return gzip.open(path, mode=mode)
+
def _open_bz2(path, mode):
import bz2
- return bz2.BZ2File(path,mode=mode)
+ return bz2.BZ2File(path, mode=mode)
+
# To handle new extensions, define a function accepting a `path` and `mode`.
# Then add the extension to _dispatch_dict.
-_dispatch_dict = defaultdict(lambda : open)
+_dispatch_dict = defaultdict(lambda: open)
_dispatch_dict['.gz'] = _open_gz
_dispatch_dict['.bz2'] = _open_bz2
_dispatch_dict['.gzip'] = _open_gz
diff --git a/networkx/utils/misc.py b/networkx/utils/misc.py
index 7e1dfba2..ba5ca78c 100644
--- a/networkx/utils/misc.py
+++ b/networkx/utils/misc.py
@@ -47,11 +47,12 @@ except ImportError:
total = func(total, element)
yield total
-### some cookbook stuff
+# some cookbook stuff
# used in deciding whether something is a bunch of nodes, edges, etc.
# see G.add_nodes and others in Graph Class in networkx/base.py
-def is_string_like(obj): # from John Hunter, types-free version
+
+def is_string_like(obj): # from John Hunter, types-free version
"""Check if obj is string."""
try:
obj + ''
@@ -59,15 +60,18 @@ def is_string_like(obj): # from John Hunter, types-free version
return False
return True
+
def iterable(obj):
""" Return True if obj is iterable with a well-defined len()."""
- if hasattr(obj,"__iter__"): return True
+ if hasattr(obj, "__iter__"):
+ return True
try:
len(obj)
except:
return False
return True
+
def flatten(obj, result=None):
""" Return flattened version of (possibly nested) iterable object. """
if not iterable(obj) or is_string_like(obj):
@@ -81,13 +85,17 @@ def flatten(obj, result=None):
flatten(item, result)
return obj.__class__(result)
-def is_list_of_ints( intlist ):
+
+def is_list_of_ints(intlist):
""" Return True if list is a list of ints. """
- if not isinstance(intlist,list): return False
+ if not isinstance(intlist, list):
+ return False
for i in intlist:
- if not isinstance(i,int): return False
+ if not isinstance(i, int):
+ return False
return True
+
PY2 = sys.version_info[0] == 2
if PY2:
def make_str(x):
@@ -114,6 +122,7 @@ def generate_unique_node():
""" Generate a unique node label."""
return str(uuid.uuid1())
+
def default_opener(filename):
"""Opens `filename` using system's default program.
@@ -133,7 +142,7 @@ def default_opener(filename):
call(cmd)
-def dict_to_numpy_array(d,mapping=None):
+def dict_to_numpy_array(d, mapping=None):
"""Convert a dictionary of dictionaries to a numpy array
with optional mapping."""
try:
@@ -141,30 +150,32 @@ def dict_to_numpy_array(d,mapping=None):
except (AttributeError, TypeError):
# AttributeError is when no mapping was provided and v.keys() fails.
# TypeError is when a mapping was provided and d[k1][k2] fails.
- return dict_to_numpy_array1(d,mapping)
+ return dict_to_numpy_array1(d, mapping)
-def dict_to_numpy_array2(d,mapping=None):
+
+def dict_to_numpy_array2(d, mapping=None):
"""Convert a dictionary of dictionaries to a 2d numpy array
with optional mapping.
"""
import numpy
if mapping is None:
- s=set(d.keys())
- for k,v in d.items():
+ s = set(d.keys())
+ for k, v in d.items():
s.update(v.keys())
- mapping=dict(zip(s,range(len(s))))
- n=len(mapping)
+ mapping = dict(zip(s, range(len(s))))
+ n = len(mapping)
a = numpy.zeros((n, n))
for k1, i in mapping.items():
for k2, j in mapping.items():
try:
- a[i,j]=d[k1][k2]
+ a[i, j] = d[k1][k2]
except KeyError:
pass
return a
-def dict_to_numpy_array1(d,mapping=None):
+
+def dict_to_numpy_array1(d, mapping=None):
"""Convert a dictionary of numbers to a 1d numpy array
with optional mapping.
@@ -172,14 +183,15 @@ def dict_to_numpy_array1(d,mapping=None):
import numpy
if mapping is None:
s = set(d.keys())
- mapping = dict(zip(s,range(len(s))))
+ mapping = dict(zip(s, range(len(s))))
n = len(mapping)
a = numpy.zeros(n)
- for k1,i in mapping.items():
+ for k1, i in mapping.items():
i = mapping[k1]
a[i] = d[k1]
return a
+
def is_iterator(obj):
"""Returns True if and only if the given object is an iterator
object.