Statistics
| Branch: | Revision:

root / fiddle / boost-networkx-comparision / src / networkx_graph.py @ 1705a309

History | View | Annotate | Download (2.25 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_print_centrality(graph, file_suffix):
9
    print "\n### Centrality ###"
10
    score = nx.betweenness_centrality(graph)
11
    for node, centrality in score.iteritems():
12
        print "%s\t%f" % (node, centrality)
13

    
14
    with open(MAIN_CODE_DIR + '/output/networkx_%s.csv' % file_suffix, 'w') as output:
15
        for node, centrality in score.iteritems():
16
            output.write('%s, %s\n' % (node, centrality))
17

    
18
def handle_edgelist(filepath):
19
    graph = nx.read_weighted_edgelist(filepath)
20
    calculate_and_print_centrality(graph, 'edge_list')
21

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

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

    
40
    # create graph with all nodes and edges and weights
41
    graph.add_weighted_edges_from(graph_data)
42

    
43
    calculate_and_print_centrality(graph, 'json_olsr')
44

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

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

    
63
    # create graph with all nodes and edges and weights
64
    graph.add_weighted_edges_from(graph_data)
65

    
66
    calculate_and_print_centrality(graph, 'json_topology')
67

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

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

    
75
    input_json_topology = MAIN_CODE_DIR + '/input/jsoninfo_topo.json'
76
    handle_json_topology(input_json_topology)