Statistics
| Branch: | Revision:

root / fiddle / boost-networkx-comparision / src / networkx_graph.py @ 37200dce

History | View | Annotate | Download (2.29 KB)

1
import json
2
import os
3
import networkx as nx
4
from pdb import set_trace as debugger
5

    
6
MAIN_CODE_DIR = os.environ.get('MAIN_CODE_DIR', '')
7

    
8
def calculate_and_write_centrality(graph, file_suffix):
9
    score = nx.betweenness_centrality(graph)
10
    # for node, centrality in score.iteritems():
11
    #     print "%s\t%f" % (node, centrality)
12

    
13
    filepath = '/output/networkx_%s.csv'  % file_suffix
14
    print "Writing centrality to %s" % filepath
15

    
16
    with open(MAIN_CODE_DIR + filepath, 'w') as output:
17
        for node, centrality in score.iteritems():
18
            output.write('%s, %s\n' % (node, centrality))
19

    
20
def handle_edgelist(filepath):
21
    graph = nx.read_weighted_edgelist(filepath)
22
    calculate_and_write_centrality(graph, 'edge_list')
23

    
24
def handle_json_olsr(filepath):
25
    # create empty graph
26
    graph = nx.Graph()
27

    
28
    json_data = open(filepath)
29
    data = json.load(json_data)
30
    graph_data = list()
31
    try:
32
        links = data['links']
33
        for link in links:
34
            source = link['source']
35
            target = link['target']
36
            cost = link['cost']
37
            graph_data.append((source, target, cost))
38
    except Exception as e:
39
        print e
40
        return 0
41

    
42
    # create graph with all nodes and edges and weights
43
    graph.add_weighted_edges_from(graph_data)
44

    
45
    calculate_and_write_centrality(graph, 'json_olsr')
46

    
47
def handle_json_topology(filepath):
48
        # create empty graph
49
    graph = nx.Graph()
50

    
51
    json_data = open(filepath)
52
    data = json.load(json_data)
53
    graph_data = list()
54
    try:
55
        links = data['topology']
56
        for link in links:
57
            source = link['lastHopIP']
58
            target = link['destinationIP']
59
            cost = link['neighborLinkQuality']
60
            graph_data.append((source, target, cost))
61
    except Exception as e:
62
        print e
63
        return 0
64

    
65
    # create graph with all nodes and edges and weights
66
    graph.add_weighted_edges_from(graph_data)
67

    
68
    calculate_and_write_centrality(graph, 'json_topology')
69

    
70
if __name__ == '__main__':
71
    input_edgelist = MAIN_CODE_DIR + '/input/ninux_30_1.edges'
72
    handle_edgelist(input_edgelist)
73

    
74
    input_json_olsr = MAIN_CODE_DIR + '/input/olsr-netjson.json'
75
    handle_json_olsr(input_json_olsr)
76

    
77
    input_json_topology = MAIN_CODE_DIR + '/input/jsoninfo_topo.json'
78
    handle_json_topology(input_json_topology)