wcn_emulator / graph_utils.py @ b1497c9f
History | View | Annotate | Download (2.62 KB)
1 |
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 |
G.add_edge(link["source"], link["target"], |
36 |
{"weight": cost})
|
37 |
return G
|
38 |
|
39 |
|
40 |
def loadGraph(fname, remap=False, connected=True, silent=False): |
41 |
""" Parameters
|
42 |
--------------
|
43 |
fname : string
|
44 |
filname to open
|
45 |
remap : bool
|
46 |
remap the labels to a sequence of integers
|
47 |
connected : bool
|
48 |
return only the larges component subgraph
|
49 |
|
50 |
"""
|
51 |
G = nx.Graph() |
52 |
if not silent: |
53 |
print "Loading/Generating Graph" |
54 |
# load a file using networkX adjacency matrix structure
|
55 |
if fname.lower().endswith(".adj"): |
56 |
try:
|
57 |
G = nx.read_adjlist(fname, nodetype=int)
|
58 |
except IOError as err: |
59 |
print
|
60 |
print err
|
61 |
sys.exit(1)
|
62 |
# load a file using networkX .edges structure
|
63 |
elif fname.lower().endswith(".edges"): |
64 |
try:
|
65 |
G = nx.read_weighted_edgelist(fname, nodetype=int)
|
66 |
except IOError as err: |
67 |
print
|
68 |
print err
|
69 |
sys.exit(1)
|
70 |
# load a a network in NetJSON format
|
71 |
elif fname.lower().endswith(".json"): |
72 |
try:
|
73 |
G = load_json(fname) |
74 |
except IOError as err: |
75 |
print
|
76 |
print err
|
77 |
sys.exit(1)
|
78 |
else:
|
79 |
print >> sys.stderr, "Error: Allowed file extensions are .adj for",\ |
80 |
"adjacency matrix, .json for netjson and .edges for edge-list"
|
81 |
sys.exit(1)
|
82 |
if connected:
|
83 |
C = sorted(list(nx.connected_component_subgraphs(G)), |
84 |
key=len, reverse=True)[0] |
85 |
G = C |
86 |
if not silent: |
87 |
print >> sys.stderr, "Graph", fname, "loaded", |
88 |
# remap node labels so we don't have "holes" in the numbering
|
89 |
if remap:
|
90 |
mapping = dict(zip(G.nodes(), range(G.order()))) |
91 |
H = nx.relabel_nodes(G, mapping) |
92 |
return H
|
93 |
return G
|