Skip to content

Commit f92f5aa

Browse files
committed
Clean up and add documentation to nodal_pathlengths.
1 parent 9e392c2 commit f92f5aa

File tree

1 file changed

+30
-19
lines changed

1 file changed

+30
-19
lines changed

brainx/metrics.py

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
# Imports
66
#-----------------------------------------------------------------------------
77

8-
98
import networkx as nx
109
import numpy as np
1110
from scipy import sparse
@@ -24,34 +23,46 @@ def compute_sigma(arr,clustarr,lparr):
2423

2524
return out
2625

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:
4354
source_arr=np.array([np.nan])
4455
nodal_means[src]=source_arr.mean()
45-
#nodal_array=np.array(nodal_means)
4656
return nodal_means
4757

58+
4859
def assert_no_selfloops(G):
4960
"""Raise an error if the graph G has any selfloops.
5061
"""
5162
if G.nodes_with_selfloops():
5263
raise ValueError("input graph can not have selfloops")
5364

54-
#@profile
65+
5566
def path_lengths(G):
5667
"""Compute array of all shortest path lengths for the given graph.
5768

0 commit comments

Comments
 (0)