Statistics
| Branch: | Revision:

wcn_emulator / graph_utils.py @ master

History | View | Annotate | Download (2.61 KB)

1 b1497c9f Luca Baldesi
import json
2
import sys
3
import networkx as nx
4
5
6
def load_json(json_file):
7
    """ import a json file in NetJSON format, convert to Graph class
8
    Parameters
9
    ----------
10
    json_file : string with file path
11
    """
12
13
    try:
14
        file_p = open(json_file, "r")
15
    except IOError:
16
        raise
17
    try:
18
        netjson_net = json.load(file_p)
19
    except ValueError as err:
20
        print "Could not decode file", err
21
    # TODO add a schema to validate the subset of features we are
22
    # able to consider
23
24
    G = nx.Graph()
25
    cost_label = ""
26
    if "metric" in netjson_net and netjson_net["metric"] == "ETX":
27
        cost_label = "cost"
28
    for node in netjson_net["nodes"]:
29
        G.add_node(node["id"])
30
    for link in netjson_net["links"]:
31
        if cost_label:
32
            cost = float(link["cost"])
33
        else:
34
            cost = 1.0
35 f4919c7b Leonardo Maccari
        G.add_edge(link["source"], link["target"], attr_dict={"weight": cost})
36 b1497c9f Luca Baldesi
    return G
37
38
39
def loadGraph(fname, remap=False, connected=True, silent=False):
40
    """ Parameters
41
    --------------
42
    fname : string
43
        filname to open
44
    remap : bool
45
        remap the labels to a sequence of integers
46
    connected : bool
47
        return only the larges component subgraph
48

49
    """
50
    G = nx.Graph()
51
    if not silent:
52
        print "Loading/Generating Graph"
53
    # load a file using networkX adjacency matrix structure
54
    if fname.lower().endswith(".adj"):
55
        try:
56
            G = nx.read_adjlist(fname, nodetype=int)
57
        except IOError as err:
58
            print
59
            print err
60
            sys.exit(1)
61
    # load a file using networkX .edges structure
62
    elif fname.lower().endswith(".edges"):
63
        try:
64
            G = nx.read_weighted_edgelist(fname, nodetype=int)
65
        except IOError as err:
66
            print
67
            print err
68
            sys.exit(1)
69
    # load a a network in NetJSON format
70
    elif fname.lower().endswith(".json"):
71
        try:
72
            G = load_json(fname)
73
        except IOError as err:
74
            print
75
            print err
76
            sys.exit(1)
77
    else:
78
        print >> sys.stderr, "Error: Allowed file extensions are .adj for",\
79
            "adjacency matrix, .json for netjson and .edges for edge-list"
80
        sys.exit(1)
81
    if connected:
82
        C = sorted(list(nx.connected_component_subgraphs(G)),
83
                   key=len, reverse=True)[0]
84
        G = C
85
    if not silent:
86
        print >> sys.stderr, "Graph", fname, "loaded",
87
    # remap node labels so we don't have "holes" in the numbering
88
    if remap:
89
        mapping = dict(zip(G.nodes(), range(G.order())))
90
        H = nx.relabel_nodes(G, mapping)
91
        return H
92
    return G