upstream/tools/graph_converter/convert_graph.py
1#!/usr/bin/env python
2# Aufruf convert_graph.py --infile datei --informat typ --outfile ausgabedatei --outformat ausgabetyp
3
4import argparse
5import sys
6
7import networkx as nx
8from networkx.readwrite import json_graph
9from xgmml_networkx import XGMMLParserHelper, XGMMLWriter
10
11# supported graph_types
12graph_types = ["gml", "yaml", "gspan", "xgmml", "gexf", "graphml", "json", "pajek"]
13
14func_dic_read = {
15 "gml": nx.read_gml,
16 "yaml": nx.read_yaml,
17 "gexf": nx.read_gexf,
18 "graphml": nx.read_graphml,
19 "pajek": nx.read_pajek,
20}
21
22func_dic_write = {
23 "gml": nx.write_gml,
24 "yaml": nx.write_yaml,
25 "gexf": nx.write_gexf,
26 "graphml": nx.write_graphml,
27 "pajek": nx.write_pajek,
28}
29
30# completely supported types by networkx
31completely_supported_types = ["gml", "gexf", "yaml", "graphml", "pajek"]
32
33
34def read_gspan(infile):
35 G = nx.DiGraph()
36 idoffset = 0
37 old_id_start = 0
38 for line in infile:
39 line_split = line.split(" ")
40 length_split = len(line_split)
41 if line[0] == "v":
42 G.add_node(idoffset, label=line_split[2].strip())
43 idoffset += 1
44 elif line[0] == "e":
45 if length_split < 3:
46 raise Exception # InvalidGraph(line)
47 elif length_split > 3:
48 G.add_edge(
49 old_id_start + int(line_split[1]),
50 old_id_start + int(line_split[2]),
51 label=line_split[3].strip(),
52 )
53 else:
54 G.add_edge(
55 old_id_start + int(line_split[1]),
56 old_id_start + int(line_split[2]),
57 label="",
58 )
59 elif line[0] == "t":
60 # its a new subgraph
61 # idoffset*=1
62 old_id_start = idoffset
63 # print(nx.is_connected(G))
64 return G
65
66
67def write_gspan(graph, outfile):
68 # get all subgraphs only works with undirected
69 subgraphs = nx.connected_components(graph.to_undirected())
70 id_count = 1
71 node_count = 0
72 # get labels
73 label_dic = nx.get_node_attributes(graph, "label")
74 for s in subgraphs:
75 node_count_tree = 0
76 node_dict = {}
77 outfile.write("t # id " + str(id_count) + "\n")
78 # for every node in subgraph
79 for v in sorted(s):
80 # node id restart from 0 for every sub graph
81 node_dict[v] = node_count_tree
82 outfile.write("v " + str(node_count_tree) + " " + label_dic[v] + " \n")
83 node_count_tree += 1
84 node_count += 1
85
86 # all edges adjacent to a node of s
87 edges = nx.edges(graph, s)
88 for e in sorted(edges):
89 # print(graph[e[0]][e[1]])
90 try:
91 outfile.write(
92 "e "
93 + str(node_dict[e[0]])
94 + " "
95 + str(node_dict[e[1]])
96 + " "
97 + graph[e[0]][e[1]]["label"]
98 + "\n"
99 )
100 except KeyError:
101 outfile.write("e " + str(node_dict[e[0]]) + " " + str(node_dict[e[1]]))
102
103 id_count += 1
104
105
106def read_json(file):
107 json_string = file.read()
108 # print(json_string)
109 json_dict = json_graph.loads(json_string)
110 # print(json_dict)
111 # return json_graph.node_link_graph(json_dict, True, False)
112 return json_dict
113
114
115def write_json(graph, outfile):
116 json_dict = json_graph.node_link_data(graph)
117 json_string = json_graph.dumps(json_dict)
118 outfile.write(json_string)
119 # print("did it")
120
121
122def main(args):
123
124 if args.informat not in graph_types:
125 print("EXCEPTION COMPUTER EXPLODING")
126 # everything networkx can do by itself ;)
127 elif args.informat in completely_supported_types:
128 function = func_dic_read[args.informat]
129 graph = function(args.infile)
130 elif args.informat == "gspan":
131 graph = read_gspan(args.infile)
132 elif args.informat == "json":
133 graph = read_json(args.infile)
134 elif args.informat == "xgmml":
135 xgmml = XGMMLParserHelper()
136 xgmml.parseFile(args.infile)
137 graph = xgmml.graph()
138
139 if args.outformat in completely_supported_types:
140 function = func_dic_write[args.outformat]
141 function(graph, args.outfile)
142 elif args.outformat == "gspan":
143 write_gspan(graph, args.outfile)
144 elif args.outformat == "json":
145 write_json(graph, args.outfile)
146 elif args.outformat == "xgmml":
147 # xgmml=XGMMLParserHelper(graph)
148 # xgmml.parseFile(open(sys.argv[1]))
149 XGMMLWriter(args.outfile, graph, "MyGraph")
150
151
152if __name__ == "__main__":
153
154 parser = argparse.ArgumentParser()
155 parser.add_argument(
156 "--infile",
157 type=argparse.FileType("r"),
158 help="Specify the input file representing a graph",
159 )
160 parser.add_argument(
161 "--outfile", type=argparse.FileType("w"), help="Specify one output file"
162 )
163 parser.add_argument(
164 "--informat",
165 type=str,
166 help="Specify the format of the input graph",
167 choices=graph_types,
168 )
169 parser.add_argument(
170 "--outformat",
171 type=str,
172 help="Specify the format of the output graph",
173 choices=graph_types,
174 )
175 if len(sys.argv) < 8:
176 print("Too few arguments...")
177 parser.print_help()
178 exit(1)
179 args = parser.parse_args()
180 main(args)