-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdataConverter.py
51 lines (45 loc) · 1.81 KB
/
dataConverter.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
# Read a csv file with source, target, and length and generate a standard graph
import csv
import json
from os import path
graph = []
nodes = []
dFile = []
# loading the graph from the json file located in .\graph folder
dirName = path.dirname(__file__)
fileName = path.join(dirName, 'graph/TestData.csv')
# open the CSV input file
with open(fileName, newline='') as csvfile:
dFile = list(csv.DictReader(csvfile, delimiter=',', quotechar='|'))
# read the nodes and add them to nodes list
for row in dFile:
if (int(row['source']) not in nodes):
nodes.append(int(row['source']))
if (int(row['target']) not in nodes):
nodes.append(int(row['target']))
# sort the nodes list and initialize the graph
nodes.sort()
index = 0
while index < len(nodes):
graph.append({'id': index, 'gid': nodes[index],
'lat': 0, 'lon': 0, 'nbrs': [], 'dists': []})
index += 1
# update the neighbor nodes in the graph
for row in dFile:
s = nodes.index(int(row['source']))
t = nodes.index(int(row['target']))
graph[s]['lat'] = float(row['y1'])
graph[s]['lon'] = float(row['x1'])
graph[t]['lat'] = float(row['y2'])
graph[t]['lon'] = float(row['x2'])
if (t != s): # edges starting and ending at the same node are useless
if (t not in graph[s]['nbrs']):
graph[s]['nbrs'].append(t)
graph[s]['dists'].append(float(row['dist']))
if (s not in graph[t]['nbrs']):
graph[t]['nbrs'].append(s)
graph[t]['dists'].append(float(row['dist']))
# stroing graph.json file in the graph folder. It will overwrite existing files
fileName = path.join(dirName, 'graph/graph.json')
with open(fileName, 'w') as fp:
json.dump(graph, fp)