Statistics
| Branch: | Revision:

root / globecomm / heuristic_bc / utility.py @ bd3d6dca

History | View | Annotate | Download (2.46 KB)

1
import json
2
import os
3
import networkx as nx
4
import matplotlib.pyplot as plt
5
import betweenness_centrality as centrality
6

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

    
9
def initialize():
10
    """
11
    Create all necessary folder
12
    """
13
    output_dir = os.path.join(MAIN_CODE_DIR, 'output')
14
    if not os.path.isdir(output_dir):
15
        os.makedirs(output_dir)
16

    
17
    visualization_dir = os.path.join(output_dir, 'visualization')
18
    if not os.path.isdir(visualization_dir):
19
        os.makedirs(visualization_dir)
20

    
21
def weight_betweenness_centrality(graph, file_suffix):
22
    score = centrality.weight_betweenness_centrality(graph, rescale=True)
23
    filepath = '/output/weight_basic_%s.csv'  % file_suffix
24

    
25
    with open(MAIN_CODE_DIR + filepath, 'w') as output:
26
        for node, bc in score.iteritems():
27
            output.write('%s, %s\n' % (node, bc))
28

    
29
def brandes_betweenness_centrality(graph, file_suffix):
30
    score = nx.betweenness_centrality(graph, endpoints=False, normalized=False)
31
    # score = nx.betweenness_centrality(graph, endpoints=True)
32
    filepath = '/output/networkx_%s.csv'  % file_suffix
33

    
34
    with open(MAIN_CODE_DIR + filepath, 'w') as output:
35
        for node, bc in score.iteritems():
36
            output.write('%s, %s\n' % (node, bc))
37

    
38
def brandes_betweenness_centrality_endpoints(graph, file_suffix):
39
    score = nx.betweenness_centrality(graph, endpoints=True, normalized=True)
40
    filepath = '/output/networkx_%s.csv'  % file_suffix
41

    
42
    with open(MAIN_CODE_DIR + filepath, 'w') as output:
43
        for node, bc in score.iteritems():
44
            output.write('%s, %s\n' % (node, bc))
45

    
46
def read_complex_json(filepath):
47
    """Returns a graph object
48
    """
49
    edges = []
50
    with open(filepath) as f:
51
        doc = json.loads(f.read())
52
        topologies = doc["topology"]
53
        for connection in topologies:
54
            source = connection['lastHopIP']
55
            target = connection['destinationIP']
56
            cost = connection['neighborLinkQuality']
57
            edges.append((source, target, {'weight': cost}))
58

    
59
    graph = nx.Graph()
60
    print "Edges = %i\n" % len(edges)
61
    graph.add_edges_from(edges)
62
    return graph
63

    
64

    
65
def plot_graph(output_filepath, graph, title=""):
66
    plt.figure(1, figsize=(15, 10))
67
    plt.title(title)
68
    pos=nx.spring_layout(graph)
69
    colors=range(30)
70
    nx.draw(graph, pos, node_size=1000, with_label=True)
71
    nx.draw_networkx_labels(graph,pos,font_size=20,font_family='sans-serif')
72
    plt.savefig(output_filepath)
73
    plt.close()
74
    # plt.show()
75