Skip to content

Commit c8f67e5

Browse files
committed
Merge pull request #4 from cindeem/edits
GraphPartition value checking and cleaning
2 parents a9fd05a + b9fa1e3 commit c8f67e5

File tree

2 files changed

+53
-49
lines changed

2 files changed

+53
-49
lines changed

brainx/modularity.py

Lines changed: 34 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,17 @@ def __init__(self, graph, index):
7171
objects.
7272
"""
7373
# Store references to the original graph and label dict
74+
if not type(index) == type({}):
75+
raise TypeError('index should be of type dict(), not %s'%type(index))
76+
7477
self.index = copy.deepcopy(index)
75-
#self.graph = graph
7678

79+
## add quick check to make sure the passed index is
80+
## a dict of sets
81+
self._check_index_contains_sets()
82+
## raise useful error if index is missing nodes in graph
83+
self._check_allnodes_in_index(graph)
84+
7785
# We'll need the graph's adjacency matrix often, so store it once
7886
self.graph_adj_matrix = nx.adj_matrix(graph)
7987

@@ -102,6 +110,25 @@ def copy(self):
102110
def __len__(self):
103111
return len(self.index)
104112

113+
114+
def _check_index_contains_sets(self):
115+
""" the index in a GraphPartition is a dict of node sets
116+
validate that the values of this dict are all of type(set)"""
117+
index_types = [ type(x) for x in self.index.values() ]
118+
if not all([ x== type(set()) for x in index_types]):
119+
raise TypeError('index values should be of type set():: %s'%(index_types))
120+
121+
def _check_allnodes_in_index(self, graph):
122+
"""Check that index contains all nodes in graph"""
123+
sets = self.index.values()
124+
all = []
125+
for item in sets:
126+
all += list(item)
127+
if not sorted(all) == sorted(graph.nodes()):
128+
missing = [x for x in all if not x in graph.nodes()]
129+
raise ValueError('index does not contain all nodes: missing %s'%missing)
130+
131+
105132
def _edge_info(self, mod_e=None, mod_a=None, index=None):
106133
"""Create the vectors of edge information.
107134
@@ -116,26 +143,20 @@ def _edge_info(self, mod_e=None, mod_a=None, index=None):
116143
if mod_a is None: mod_a = [0] * num_mod
117144
if index is None: index = self.index
118145

119-
norm_factor = 1.0/(2.0*self.num_edges)
146+
norm_factor = 1.0 / (2.0 * self.num_edges)
120147
mat = self.graph_adj_matrix
121-
set_nodes = self._node_set
122-
for m,modnodes in index.iteritems():
123-
#set_modnodes=set(modnodes)
124-
#btwnnodes = list(set_nodes - modnodes)
125-
btwnnodes = list(set_nodes - set(index[m]))
148+
node_set = self._node_set
149+
for m, modnodes in index.iteritems():
150+
btwnnodes = list(node_set - modnodes)
126151
modnodes = list(modnodes)
127-
#why isnt' self.index a set already? graph_partition.index[m]
128-
#looks like a set when we read it in ipython
129152
mat_within = mat[modnodes,:][:,modnodes]
130153
mat_between = mat[modnodes,:][:,btwnnodes]
131154
perc_within = mat_within.sum() * norm_factor
132155
perc_btwn = mat_between.sum() * norm_factor
133156
mod_e[m] = perc_within #all of the E's
134157
mod_a[m] = perc_btwn+perc_within #all of the A's
135-
#mod_e.append(perc_within)
136-
#mod_a.append(perc_btwn+perc_within)
137158
if np.isnan(mod_e[m]) or np.isnan(mod_a[m]):
138-
1/0
159+
raise ArithmaticError('NAN found: mod_e=%s, mod_a=%s'%(mod_e[m], mod_a[m]))
139160

140161
return mod_e, mod_a
141162

@@ -154,42 +175,9 @@ def modularity_newman(self):
154175
1/0
155176
return (np.array(self.mod_e) - (np.array(self.mod_a)**2)).sum()
156177

178+
##TODO can we remove this?? CM
157179
modularity = modularity_newman
158180

159-
#modularity = modularity_guimera
160-
161-
162-
## def modularity_guimera(self, g, part):
163-
## """This function takes in a graph and a partition and returns Newman's
164-
## modularity for that graph"""
165-
166-
## """ Parameters
167-
## # g = graph part = partition; a dictionary that contains a list of
168-
## # nodes that make up that module"""
169-
170-
## #graph values
171-
## num_mod = len(part)
172-
## L = nx.number_of_edges(g)
173-
## # construct an adjacency matrix from the input graph (g)
174-
## mat = nx.adj_matrix(g)
175-
176-
## M = 0
177-
## # loop over the modules in the graph, create an adjacency matrix
178-
## for m, val in part.iteritems():
179-
## #create a 'sub mat'
180-
## submat = mat[val,:][:,val]
181-
182-
## #make a graph
183-
## subg = nx.from_numpy_matrix(submat)
184-
185-
## #calculate module-specific metrics
186-
## link_s = float(subg.number_of_edges())
187-
## deg_s = np.sum(nx.degree(g,val), dtype=float)
188-
189-
## #compute modularity!
190-
## M += ((link_s/L) - (deg_s/(2*L))**2)
191-
192-
## return M
193181

194182
def compute_module_merge(self, m1, m2):
195183
"""Merges two modules in a given partition.

brainx/tests/test_modularity.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,8 +425,9 @@ def test_mutual_information():
425425
#split modules and check that mutual information comes out
426426
#correclty/lower
427427
graph_partition3 = mod.GraphPartition(g,ppart)
428-
n1 = list(graph_partition3.index[0])[::2]
429-
n2 = list(graph_partition3.index[0])[1::2]
428+
n1 = set(list(graph_partition3.index[0])[::2])
429+
n2 = set(list(graph_partition3.index[0])[1::2])
430+
430431
split_modules,e_new,a_new,d,t,m,n1,n2 = graph_partition3.compute_module_split(0,n1,n2)
431432
graph_partition3.apply_module_split(m,n1,n2,split_modules,e_new,a_new)
432433
mi3 = mod.mutual_information(ppart,graph_partition3.index)
@@ -752,7 +753,22 @@ def test_adjust_partition():
752753
def test_empty_graphpartition():
753754
g = nx.Graph()
754755
g.add_node(1)
755-
npt.assert_raises(ValueError, mod.GraphPartition, g, {1: g.nodes()})
756+
npt.assert_raises(ValueError, mod.GraphPartition, g, {1: set(g.nodes())})
757+
758+
759+
def test_badindex_graphpartition():
760+
""" when making a GraphPArtition, check index is valid"""
761+
## index should be dict of sets
762+
e = np.loadtxt(os.path.join(os.path.dirname(__file__), 'jazz.net'),
763+
skiprows=3, dtype=int)[:, :2] - 1
764+
g = nx.Graph()
765+
g.add_edges_from(e)
766+
index = {0: set(g.nodes()[:100]), 1: set(g.nodes()[100:])}
767+
gp = mod.GraphPartition(g, index)
768+
nt.assert_true(gp.index == index)
769+
npt.assert_raises(TypeError, mod.GraphPartition, g, {0: g.nodes()})
770+
npt.assert_raises(ValueError, mod.GraphPartition, g, {0:set(g.nodes()[:-1])})
771+
npt.assert_raises(TypeError, mod.GraphPartition, g, g.nodes())
756772

757773

758774
if __name__ == "__main__":

0 commit comments

Comments
 (0)