Skip to content

Commit ca76b2a

Browse files
author
CindeeM
committed
NF: graphpartition will raise error if passed weighted matrix, new code to find solitary (unconnected) nodes
1 parent d40473c commit ca76b2a

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

brainx/modularity.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,11 @@ def __init__(self, graph, index):
7878

7979
# We'll need the graph's adjacency matrix often, so store it once
8080
self.graph_adj_matrix = nx.adj_matrix(graph)
81+
#make sure adj_matrix is binary otherwise raise exception
82+
if not self.graph_adj_matrix.sum() == \
83+
self.graph_adj_matrix.astype(bool).sum():
84+
raise ValueError('Adjacency matrix is weighted, need binary matrix')
85+
8186

8287
# Just to be sure, we don't want to count self-links, so we zero out the
8388
# diagonal.
@@ -175,6 +180,12 @@ def modularity_newman(self):
175180
modularity = modularity_newman
176181

177182

183+
def find_solitary(self):
184+
""" checks for nodes in graph with no edges """
185+
graph = nx.from_numpy_matrix(self.graph_adj_matrix)
186+
solitary=[ n for n,d in graph.degree_iter() if d==0 ]
187+
return solitary
188+
178189
def compute_module_merge(self, m1, m2):
179190
"""Merges two modules in a given partition.
180191

brainx/tests/test_modularity.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,21 @@ def test_graphpartition():
5656
index = {0:set([0,1]), 1:set([2,3])}
5757
gpart = mod.GraphPartition(graph, index)
5858
assert gpart._node_set == set([0,1,2,3])
59+
# test raise error if matrix unweighted
60+
jnk = np.random.random((10,10))
61+
jnk = np.triu(jnk,1)
62+
graph = nx.from_numpy_matrix(jnk, nx.Graph(weighted=False))
63+
npt.assert_raises(ValueError, mod.GraphPartition, graph, index)
64+
65+
def test_find_solitary():
66+
jnk = np.zeros((10,10))
67+
jnk[:6,:6] = 1
68+
jnk = np.triu(jnk,1)
69+
graph = nx.from_numpy_matrix(jnk>0, nx.Graph(weighted=False))
70+
index = {0:set([0,1,2,3,4,5,6,7,8,9])}
71+
graph_partition = mod.GraphPartition(graph, index)
72+
solitary_nodes = graph_partition.find_solitary()
73+
npt.assert_equal(solitary_nodes, [6,7,8,9])
5974

6075
def test_index_as_node_names():
6176
graph = nx.Graph()

0 commit comments

Comments
 (0)