5
5
# Imports
6
6
#-----------------------------------------------------------------------------
7
7
8
-
9
8
import networkx as nx
10
9
import numpy as np
11
10
from scipy import sparse
@@ -24,34 +23,46 @@ def compute_sigma(arr,clustarr,lparr):
24
23
25
24
return out
26
25
27
- def nodal_pathlengths (G ,n_nodes ):
28
- """ Compute mean path length for each node.
29
- Note: it is unclear how to treat infinite path lengths. For now, I replace them with np.inf, but this may make taking the mean later on difficult
30
- Inputs: G graph data output from mkgraph; n_nodes number of nodes in graph"""
31
- nodal_means = np .zeros ((n_nodes ),dtype = float )
32
- lengths = nx .all_pairs_shortest_path_length (G )
33
- for src ,pair in lengths .iteritems ():
34
- source_paths = []
35
- source_arr = np .array ([])
36
- for targ ,val in pair .items ():
37
- if src == targ :
38
- continue # we want to include src,target repeats, right?
39
- source_paths .append (float (val ))
40
- source_arr = np .array (source_paths )
41
-
42
- if source_arr .size == 0 : #make the mean path length 0 if node is disconnected
26
+
27
+ def nodal_pathlengths (G , n_nodes ):
28
+ """Compute mean path length for each node.
29
+
30
+ Parameters
31
+ ----------
32
+ G: networkx Graph
33
+ An undirected graph.
34
+
35
+ n_nodes: integer
36
+ Number of nodes in G.
37
+
38
+ Returns
39
+ -------
40
+ nodal_means: numpy array
41
+ Array of length n_nodes with each node's mean shortest path
42
+ length to other nodes. For disconnected nodes, the value in
43
+ this array is np.nan.
44
+
45
+ """
46
+ # float is the default dtype for np.zeros, but we'll choose it explicitly
47
+ # in case numpy ever changes the default to something else.
48
+ nodal_means = np .zeros (n_nodes , dtype = float )
49
+ lengths = nx .all_pairs_shortest_path_length (G )
50
+ for src , pair in lengths .iteritems ():
51
+ source_arr = np .array ([val for targ , val in pair .iteritems () if src !=
52
+ targ ], dtype = float )
53
+ if source_arr .size == 0 :
43
54
source_arr = np .array ([np .nan ])
44
55
nodal_means [src ]= source_arr .mean ()
45
- #nodal_array=np.array(nodal_means)
46
56
return nodal_means
47
57
58
+
48
59
def assert_no_selfloops (G ):
49
60
"""Raise an error if the graph G has any selfloops.
50
61
"""
51
62
if G .nodes_with_selfloops ():
52
63
raise ValueError ("input graph can not have selfloops" )
53
64
54
- #@profile
65
+
55
66
def path_lengths (G ):
56
67
"""Compute array of all shortest path lengths for the given graph.
57
68
0 commit comments