13
13
# Functions
14
14
#-----------------------------------------------------------------------------
15
15
16
- def inter_node_distances (G , n_nodes ):
17
- """Compute the shortest path lengths between all nodes in G .
16
+ def inter_node_distances (graph ):
17
+ """Compute the shortest path lengths between all nodes in graph .
18
18
19
19
This performs the same operation as NetworkX's
20
20
all_pairs_shortest_path_lengths with two exceptions: Here, self
@@ -25,24 +25,17 @@ def inter_node_distances(G, n_nodes):
25
25
26
26
Parameters
27
27
----------
28
- G : networkx Graph
28
+ graph : networkx Graph
29
29
An undirected graph.
30
30
31
- n_nodes: integer
32
- Number of nodes in G.
33
-
34
31
Returns
35
32
-------
36
33
lengths: dictionary
37
34
Dictionary of shortest path lengths keyed by source and target.
38
35
39
- Notes
40
- -----
41
- This function assumes the nodes are labeled 0 to n_nodes - 1.
42
-
43
36
"""
44
- lengths = nx .all_pairs_shortest_path_length (G )
45
- node_labels = range ( n_nodes )
37
+ lengths = nx .all_pairs_shortest_path_length (graph )
38
+ node_labels = sorted ( lengths )
46
39
for src in node_labels :
47
40
lengths [src ].pop (src )
48
41
for targ in node_labels :
@@ -66,17 +59,14 @@ def compute_sigma(arr,clustarr,lparr):
66
59
return out
67
60
68
61
69
- def nodal_pathlengths (G , n_nodes ):
62
+ def nodal_pathlengths (graph ):
70
63
"""Compute mean path length for each node.
71
64
72
65
Parameters
73
66
----------
74
- G : networkx Graph
67
+ graph : networkx Graph
75
68
An undirected graph.
76
69
77
- n_nodes: integer
78
- Number of nodes in G.
79
-
80
70
Returns
81
71
-------
82
72
nodal_means: numpy array
@@ -85,28 +75,24 @@ def nodal_pathlengths(G, n_nodes):
85
75
86
76
Notes
87
77
-----
88
- This function assumes the nodes are labeled 0 to n_nodes - 1.
89
-
90
78
Per the Brain Connectivity Toolbox for Matlab, the distance between
91
79
one node and another that cannot be reached from it is set to
92
80
infinity.
93
81
94
82
"""
95
- lengths = inter_node_distances (G , n_nodes )
96
- # It's important we iterate through range(n_nodes) rather than the keys
97
- # of lengths, as the keys are not guaranteed to be in ascending order.
98
- nodal_means = [np .mean (lengths [src ].values ()) for src in range (n_nodes )]
83
+ lengths = inter_node_distances (graph )
84
+ nodal_means = [np .mean (lengths [src ].values ()) for src in sorted (lengths )]
99
85
return np .array (nodal_means )
100
86
101
87
102
- def assert_no_selfloops (G ):
103
- """Raise an error if the graph G has any selfloops.
88
+ def assert_no_selfloops (graph ):
89
+ """Raise an error if the graph graph has any selfloops.
104
90
"""
105
- if G .nodes_with_selfloops ():
91
+ if graph .nodes_with_selfloops ():
106
92
raise ValueError ("input graph can not have selfloops" )
107
93
108
94
109
- def path_lengths (G ):
95
+ def path_lengths (graph ):
110
96
"""Compute array of all shortest path lengths for the given graph.
111
97
112
98
The length of the output array is the number of unique pairs of nodes that
@@ -118,12 +104,12 @@ def path_lengths(G):
118
104
119
105
Parameters
120
106
----------
121
- G : an undirected graph object.
107
+ graph : an undirected graph object.
122
108
"""
123
109
124
- assert_no_selfloops (G )
110
+ assert_no_selfloops (graph )
125
111
126
- length = nx .all_pairs_shortest_path_length (G )
112
+ length = nx .all_pairs_shortest_path_length (graph )
127
113
paths = []
128
114
seen = set ()
129
115
for src ,targets in length .iteritems ():
@@ -136,7 +122,7 @@ def path_lengths(G):
136
122
137
123
138
124
#@profile
139
- def path_lengthsSPARSE (G ):
125
+ def path_lengthsSPARSE (graph ):
140
126
"""Compute array of all shortest path lengths for the given graph.
141
127
142
128
XXX - implementation using scipy.sparse. This might be faster for very
@@ -153,14 +139,14 @@ def path_lengthsSPARSE(G):
153
139
154
140
Parameters
155
141
----------
156
- G : an undirected graph object.
142
+ graph : an undirected graph object.
157
143
"""
158
144
159
- assert_no_selfloops (G )
145
+ assert_no_selfloops (graph )
160
146
161
- length = nx .all_pairs_shortest_path_length (G )
147
+ length = nx .all_pairs_shortest_path_length (graph )
162
148
163
- nnod = G .number_of_nodes ()
149
+ nnod = graph .number_of_nodes ()
164
150
paths_mat = sparse .dok_matrix ((nnod ,nnod ))
165
151
166
152
for src ,targets in length .iteritems ():
@@ -170,66 +156,59 @@ def path_lengthsSPARSE(G):
170
156
return sparse .triu (paths_mat ,1 ).data
171
157
172
158
173
- def glob_efficiency (G ):
159
+ def glob_efficiency (graph ):
174
160
"""Compute array of global efficiency for the given graph.
175
161
176
162
Global efficiency: returns a list of the inverse path length matrix
177
163
across all nodes The mean of this value is equal to the global efficiency
178
164
of the network."""
179
165
180
- return 1.0 / path_lengths (G )
166
+ return 1.0 / path_lengths (graph )
181
167
182
168
183
- def nodal_efficiency (G , n_nodes ):
184
- """Return array with nodal efficiency for each node in G .
169
+ def nodal_efficiency (graph ):
170
+ """Return array with nodal efficiency for each node in graph .
185
171
186
172
See Achard and Bullmore (2007, PLoS Comput Biol) for the definition
187
173
of nodal efficiency.
188
174
189
175
Parameters
190
176
----------
191
- G : networkx Graph
177
+ graph : networkx Graph
192
178
An undirected graph.
193
179
194
- n_nodes: integer
195
- Number of nodes in G.
196
-
197
180
Returns
198
181
-------
199
182
nodal_efficiencies: numpy array
200
- An array with the nodal efficiency for each node in G , in
183
+ An array with the nodal efficiency for each node in graph , in
201
184
the order specified by node_labels. The array is in ascending
202
185
order of node labels.
203
186
204
187
Notes
205
188
-----
206
- This function assumes the nodes are labeled 0 to n_nodes - 1.
207
-
208
189
Per the Brain Connectivity Toolbox for Matlab, the distance between
209
190
one node and another that cannot be reached from it is set to
210
191
infinity.
211
192
212
193
"""
213
- nodal_efficiencies = np .zeros (n_nodes , dtype = float )
214
- lengths = inter_node_distances (G , n_nodes )
215
- # It's important we iterate through range(n_nodes) rather than the keys
216
- # of lengths, as the keys are not guaranteed to be in ascending order.
217
- for src in range (n_nodes ):
194
+ lengths = inter_node_distances (graph )
195
+ nodal_efficiencies = np .zeros (len (lengths ), dtype = float )
196
+ for src in sorted (lengths ):
218
197
inverse_paths = [1.0 / val for val in lengths [src ].itervalues ()]
219
198
nodal_efficiencies [src ] = np .mean (inverse_paths )
220
199
return nodal_efficiencies
221
200
222
201
223
- def local_efficiency (G ):
202
+ def local_efficiency (graph ):
224
203
"""Compute array of global efficiency for the given grap.h
225
204
226
205
Local efficiency: returns a list of paths that represent the nodal
227
206
efficiencies across all nodes with their direct neighbors"""
228
207
229
208
nodepaths = []
230
- length = nx .all_pairs_shortest_path_length (G )
231
- for n in G .nodes ():
232
- nneighb = nx .neighbors (G ,n )
209
+ length = nx .all_pairs_shortest_path_length (graph )
210
+ for n in graph .nodes ():
211
+ nneighb = nx .neighbors (graph ,n )
233
212
234
213
paths = []
235
214
for src ,targets in length .iteritems ():
@@ -251,18 +230,18 @@ def local_efficiency(G):
251
230
return np .array (nodepaths )
252
231
253
232
254
- def local_efficiency (G ):
233
+ def local_efficiency (graph ):
255
234
"""Compute array of local efficiency for the given graph.
256
235
257
236
Local efficiency: returns a list of paths that represent the nodal
258
237
efficiencies across all nodes with their direct neighbors"""
259
238
260
- assert_no_selfloops (G )
239
+ assert_no_selfloops (graph )
261
240
262
241
nodepaths = []
263
- length = nx .all_pairs_shortest_path_length (G )
264
- for n in G :
265
- nneighb = set (nx .neighbors (G ,n ))
242
+ length = nx .all_pairs_shortest_path_length (graph )
243
+ for n in graph :
244
+ nneighb = set (nx .neighbors (graph ,n ))
266
245
267
246
paths = []
268
247
for nei in nneighb :
@@ -279,20 +258,20 @@ def local_efficiency(G):
279
258
return np .array (nodepaths )
280
259
281
260
282
- def dynamical_importance (G ):
283
- """Compute dynamical importance for G .
261
+ def dynamical_importance (graph ):
262
+ """Compute dynamical importance for graph .
284
263
285
264
Ref: Restrepo, Ott, Hunt. Phys. Rev. Lett. 97, 094102 (2006)
286
265
"""
287
266
# spectrum of the original graph
288
- eigvals = nx .adjacency_spectrum (G )
267
+ eigvals = nx .adjacency_spectrum (graph )
289
268
lambda0 = eigvals [0 ]
290
- # Now, loop over all nodes in G , and for each, make a copy of G , remove
269
+ # Now, loop over all nodes in graph , and for each, make a copy of graph , remove
291
270
# that node, and compute the change in lambda.
292
- nnod = G .number_of_nodes ()
271
+ nnod = graph .number_of_nodes ()
293
272
dyimp = np .empty (nnod ,float )
294
273
for n in range (nnod ):
295
- gn = G .copy ()
274
+ gn = graph .copy ()
296
275
gn .remove_node (n )
297
276
lambda_n = nx .adjacency_spectrum (gn )[0 ]
298
277
dyimp [n ] = lambda0 - lambda_n
@@ -301,22 +280,22 @@ def dynamical_importance(G):
301
280
return dyimp
302
281
303
282
304
- def weighted_degree (G ):
283
+ def weighted_degree (graph ):
305
284
"""Return an array of degrees that takes weights into account.
306
285
307
286
For unweighted graphs, this is the same as the normal degree() method
308
287
(though we return an array instead of a list).
309
288
"""
310
- amat = nx .adj_matrix (G ).A # get a normal array out of it
289
+ amat = nx .adj_matrix (graph ).A # get a normal array out of it
311
290
return abs (amat ).sum (0 ) # weights are sums across rows
312
291
313
292
314
- def graph_summary (G ):
293
+ def graph_summary (graph ):
315
294
"""Compute a set of statistics summarizing the structure of a graph.
316
295
317
296
Parameters
318
297
----------
319
- G : a graph object.
298
+ graph : a graph object.
320
299
321
300
threshold : float, optional
322
301
@@ -326,26 +305,23 @@ def graph_summary(G):
326
305
"""
327
306
328
307
# Average path length
329
- lp = path_lengths (G )
330
- clust = np .array (nx .clustering (G ).values ())
331
- glob_eff = glob_efficiency (G )
332
- loc_eff = local_efficiency (G )
308
+ lp = path_lengths (graph )
309
+ clust = np .array (nx .clustering (graph ).values ())
310
+ glob_eff = glob_efficiency (graph )
311
+ loc_eff = local_efficiency (graph )
333
312
334
313
return dict ( lp = lp .mean (), clust = clust .mean (), glob_eff = glob_eff .mean (),
335
314
loc_eff = loc_eff .mean () )
336
315
337
316
338
- def nodal_summaryOut (G , n_nodes ):
317
+ def nodal_summaryOut (graph ):
339
318
"""Compute statistics for individual nodes.
340
319
341
320
Parameters
342
321
----------
343
- G : networkx graph
322
+ graph : networkx graph
344
323
An undirected graph.
345
324
346
- n_nodes: integer
347
- Number of nodes in G.
348
-
349
325
Returns
350
326
-------
351
327
dictionary
@@ -357,22 +333,16 @@ def nodal_summaryOut(G, n_nodes):
357
333
ascending order of node labels.
358
334
359
335
"""
360
- lp = nodal_pathlengths (G , n_nodes )
361
- # As stated in the Python documentation, "Keys and values are listed in an
362
- # arbitrary order which is non-random, varies across Python
363
- # implementations, and depends on the dictionary's history of insertions
364
- # and deletions." Thus, we cannot expect, e.g., nx.clustering(G)
365
- # to have the nodes listed in ascending order, as we desire.
366
- node_labels = range (n_nodes )
367
- clust_dict = nx .clustering (G )
368
- clust = np .array ([clust_dict [n ] for n in node_labels ])
369
- b_cen_dict = nx .betweenness_centrality (G )
370
- b_cen = np .array ([b_cen_dict [n ] for n in node_labels ])
371
- c_cen_dict = nx .closeness_centrality (G )
372
- c_cen = np .array ([c_cen_dict [n ] for n in node_labels ])
373
- nod_eff = nodal_efficiency (G , n_nodes )
374
- loc_eff = local_efficiency (G )
375
- deg_dict = G .degree ()
376
- deg = [deg_dict [n ] for n in node_labels ]
336
+ lp = nodal_pathlengths (graph )
337
+ clust_dict = nx .clustering (graph )
338
+ clust = np .array ([clust_dict [n ] for n in sorted (clust_dict )])
339
+ b_cen_dict = nx .betweenness_centrality (graph )
340
+ b_cen = np .array ([b_cen_dict [n ] for n in sorted (b_cen_dict )])
341
+ c_cen_dict = nx .closeness_centrality (graph )
342
+ c_cen = np .array ([c_cen_dict [n ] for n in sorted (c_cen_dict )])
343
+ nod_eff = nodal_efficiency (graph )
344
+ loc_eff = local_efficiency (graph )
345
+ deg_dict = graph .degree ()
346
+ deg = [deg_dict [n ] for n in sorted (deg_dict )]
377
347
return dict (lp = lp , clust = clust , b_cen = b_cen , c_cen = c_cen , nod_eff = nod_eff ,
378
348
loc_eff = loc_eff , deg = deg )
0 commit comments