1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
Description: Handle empty graph (all zero matrix) and null graph (raise exception) in to_scipy_sparse_matrix.
Origin: https://networkx.lanl.gov/trac/changeset/8960521b5ae4897bdbac4ff49525d8b37bff88d2/networkx
Index: networkx/convert.py
===================================================================
--- python-networkx-1.7rc1.orig/networkx/convert.py (revision 2066)
+++ python-networkx-1.7rc1/networkx/convert.py (revision 2207)
@@ -776,11 +776,16 @@
nodelist = G
nlen = len(nodelist)
+ if nlen == 0:
+ raise nx.NetworkXError("Graph has no nodes or edges")
index = dict(zip(set(nodelist),range(nlen)))
if len(nodelist) != len(index):
msg = "Ambiguous ordering: `nodelist` contained duplicates."
raise nx.NetworkXError(msg)
- row,col,data=zip(*((index[u],index[v],d.get(weight,1))
- for u,v,d in G.edges(nodelist, data=True)
- if u in index and v in index))
+ if G.number_of_edges() == 0:
+ row,col,data=[],[],[]
+ else:
+ row,col,data=zip(*((index[u],index[v],d.get(weight,1))
+ for u,v,d in G.edges_iter(nodelist, data=True)
+ if u in index and v in index))
if G.is_directed():
M = sparse.coo_matrix((data,(row,col)),shape=(nlen,nlen), dtype=dtype)
Index: networkx/tests/test_convert_scipy.py
===================================================================
--- python-networkx-1.7rc1.orig/networkx/tests/test_convert_scipy.py (revision 2066)
+++ python-networkx-1.7rc1/networkx/tests/test_convert_scipy.py (revision 2207)
@@ -160,2 +160,12 @@
P4 = path_graph(4)
nx.to_scipy_sparse_matrix(P4, format='any_other')
+
+ @raises(nx.NetworkXError)
+ def test_null_fail(self):
+ nx.to_scipy_sparse_matrix(nx.Graph())
+
+ def test_empty(self):
+ G = nx.Graph()
+ G.add_node(1)
+ M = nx.to_scipy_sparse_matrix(G)
+ np_assert_equal(M.todense(), np.matrix([[0]]))
|