-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter.py
89 lines (69 loc) · 2.19 KB
/
converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 15:16:01 2020
@author: Paolo
Graph Converter
"""
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Converts graph to be run with Expected Force")
parser.add_argument("--input-file", default="test.txt",
help="input graph")
parser.add_argument("--delimiter", default=" ",
help="delimiter between parent and children node")
parser.add_argument("--outname", default="test",
help="name and location of output (no file extension)")
args = parser.parse_args()
input_file = args.input_file;
delimiter = args.delimiter;
outname = args.outname;
mappingfile = outname + "_mapping.txt"
outfile = outname + "_converted.txt"
mapping = {}
max_id = -1;
with open(input_file) as f:
n = 0;
inc = "!"
for line in f:
linesplit = line.split(delimiter)
inc = int(linesplit[0]);
max_id = max(inc,max_id);
if inc not in mapping:
mapping[inc] = n;
n += 1;
out = int(linesplit[1]);
max_id = max(out,max_id);
if out not in mapping:
mapping[out] = n;
n += 1;
print(n, "Nodes found, max id = ", max_id);
with open(mappingfile, "w") as f:
for node,nodeid in mapping.items():
f.writelines(str(node) + " " + str(nodeid) + "\n")
print("mapping saved in ", mappingfile)
graph = {}
with open(input_file) as f:
inc = "!"
for line in f:
linesplit = line.split(delimiter)
inc = mapping[int(linesplit[0])];
out = mapping[int(linesplit[1])];
if inc not in graph:
graph[inc] = [out,]
else:
if out not in graph[inc]:
graph[inc].append(out);
if out not in graph:
graph[out] = [inc,]
else:
if inc not in graph[out]:
graph[out].append(inc);
for parent, children in graph.items():
children.sort();
with open(outfile, "w") as f:
for parent in range(len(graph)):
for child in graph[parent]:
f.writelines(str(parent) + " " + str(child) + "\n");
print("graph converted saved in ", outfile)