Last active
August 29, 2015 14:04
-
-
Save bkamapantula/600bbcf7bb4800a61f89 to your computer and use it in GitHub Desktop.
finding structural properties of a network
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import networkx as nx | |
from operator import itemgetter | |
import sys | |
import os | |
import csv | |
import numpy as np | |
import math | |
def build_graph(): | |
in_file = open(sys.argv[1], 'r') | |
G = nx.Graph() | |
for row in in_file: | |
row = row.split() | |
src = int(row[0]) | |
dest = int(row[1]) | |
G.add_edge(src, dest) | |
return G | |
def all_asps(): | |
""" | |
find ASP to all nodes. | |
make the nodes with shortest ASP as sink. | |
find packet receival %. | |
""" | |
G = build_graph() | |
all_shortest_paths = [] | |
all_pairs_shortest_paths = nx.all_pairs_dijkstra_path_length(G) | |
for node in G.nodes(): | |
val = sum(all_pairs_shortest_paths[node].values())/len(all_pairs_shortest_paths[node]) | |
print "ASP to", node, ":", val | |
for sink, sink_degree in sorted(G.degree_iter(), key=itemgetter(1), reverse=True)[0:1]: | |
print "Sink = ", sink | |
all_asps() | |
def all_metrics(): | |
# input network file | |
G = build_graph() | |
metrics_file = os.path.splitext(sys.argv[1])[0] + "-metrics.txt" | |
for sink, sink_degree in sorted(G.degree_iter(), key=itemgetter(1), reverse=True)[0:1]: | |
print "Sink = ", sink | |
# eigenvector centrality | |
ec = nx.eigenvector_centrality_numpy(G) | |
# degree centrality | |
dc = nx.degree_centrality(G) | |
# betweenness centrality | |
bc = nx.betweenness_centrality(G) | |
ec_sink = ec[sink] | |
dc_sink = dc[sink] | |
bc_sink = bc[sink] | |
num_nodes = nx.number_of_nodes(G) | |
# find adjacency matrix | |
adj_mat = nx.adjacency_matrix(G) | |
# find eigen values and vectors | |
evalues, evectors = np.linalg.eig(adj_mat) | |
topological_entropy = math.log(abs(max(evalues))) | |
all_shortest_paths_to_sink = [] | |
all_shortest_paths_to_sink = [nx.dijkstra_path_length(G, node, sink) for node in G.nodes()] | |
asp = sum(all_shortest_paths_to_sink)/len(all_shortest_paths_to_sink) | |
asp = "%.2f" % asp | |
with open(metrics_file, 'w') as f: | |
a = csv.writer(f, delimiter='\t') | |
data = [ [nx.estrada_index(G),], | |
[nx.density(G),], | |
[bc_sink,], | |
[dc_sink], | |
[ec_sink], | |
[sum(ec.values()),], | |
[sum(dc.values()),], | |
[topological_entropy,], | |
[asp,] | |
] | |
"""data = [ ['Estrada Index', nx.estrada_index(G)], | |
['Density', nx.density(G)], | |
['Total Eigenvector centrality', sum(ec.values())], | |
['Total Degree centrality', sum(dc.values())] | |
]""" | |
a.writerows(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment