Skip to content

Commit 504e56d

Browse files
author
CindeeM
committed
NF: GraphPartiton new method index_as_node_names to retrieve index(partition) as node names and not as ints
1 parent 31467fb commit 504e56d

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

brainx/modularity.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ def __init__(self, graph, index):
9595
# Store the nodes as a set of contiguous integers (indices into
9696
#the adjacency_matrix), needed for many operations
9797
self._node_set = set(range(self.num_nodes))
98+
self._node_names = graph.nodes()
9899
## raise useful error if index is missing nodes in graph
99100
self._check_allnodes_in_index(graph)
100101

@@ -510,8 +511,9 @@ def random_mod(self):
510511
num_mods=len(self)
511512

512513

513-
# Make a random choice bounded between 0 and 1, less than 0.5 means we will split the modules
514-
# greater than 0.5 means we will merge the modules.
514+
# Make a random choice bounded between 0 and 1,
515+
# less than 0.5 means we will split the modules
516+
# greater than 0.5 means we will merge the modules.
515517

516518
if num_mods >= self.num_nodes-1: ### CG: why are we subtracting 1 here?
517519
coin_flip = 1 #always merge if each node is in a separate module
@@ -611,6 +613,15 @@ def store_best(self):
611613
#Store references to the original graph and label dict
612614
self.bestindex = copy.deepcopy(self.index)
613615

616+
def index_as_node_names(self):
617+
""" index by default contains references to integers represented the
618+
nodes as indexed in the adjacency matrix defined in the original graph.
619+
This will return the index (partition) using the graph node names"""
620+
named_part = []
621+
for nmod, part in self.index.iteritems():
622+
named_part.append([self._node_names[x] for x in part])
623+
return named_part
624+
614625
def check_integrity(self, partition):
615626
""" Raises error if partition structure contains
616627
empty partitions or Nan values"""

brainx/tests/test_modularity.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,18 @@ def test_graphpartition():
5555
graph.add_edge('c','d')
5656
index = {0:set([0,1]), 1:set([2,3])}
5757
gpart = mod.GraphPartition(graph, index)
58+
assert gpart._node_set == set([0,1,2,3])
5859

60+
def test_index_as_node_names():
61+
graph = nx.Graph()
62+
graph.add_edge('a','b')
63+
graph.add_edge('c','d')
64+
## NOTE network x does not store names as added
65+
## for this graph ['a', 'c', 'b', 'd']
66+
index = {0:set([0,2]), 1:set([1,3])}
67+
gpart = mod.GraphPartition(graph, index)
68+
named_index = gpart.index_as_node_names()
69+
assert ['a','b'] in named_index
5970

6071
def test_random_modular_graph_between_fraction():
6172
"""Test for graphs with non-zero between_fraction"""

0 commit comments

Comments
 (0)